sspat/reserved-words

验证字符串是否与特定PHP版本的保留字冲突

3.0.1 2022-04-11 10:29 UTC

This package is auto-updated.

Last update: 2024-09-11 15:34:04 UTC


README

Latest Version Build Mutation testing badge Test Coverage Type Coverage License

关于

此包允许检查字符串是否为PHP保留字,并允许将字符串用作PHP命名空间/类/接口/特性、函数、方法或常量名称。

默认情况下,检查将针对您当前的运行时PHP版本执行,但您可以选择任何版本进行检查。

这在代码生成时可能很有用,例如,当PHP代码基于某些用户输入生成时。

PHP文档中的保留字

安装

composer require sspat/reserved-words

用法

<?php

use sspat\ReservedWords\ReservedWords;

$reservedWords = new ReservedWords();
$word = 'list';

/**
 * Checks that the word is reserved in any PHP version.
 * It is still possible to use reserved words in php code in many places, but generally you should avoid it.
 * This method also returns true for words that are marked as "soft" reserved in the PHP docs and may
 * become reserved in future versions of the language.
 */
$isReserved = $reservedWords->isReserved($word);
/**
 * Checks that the word cannot be used as a constant name in your current php version.
 */
$cannotUseAsConstantName = $reservedWords->isReservedConstantName($word);
/**
 * Checks that the word cannot be used as a namespace part in your current php version.
 * 
 * This is used for checking parts of namespaces, not full namespace strings.
 * E.g. calling this with `Some\Namespace\String` is incorrect, you should make three separate calls
 * with `Some`, `Namespace` and `String`.
 */
$cannotUseAsNamespaceName = $reservedWords->isReservedNamespaceName($word);
/**
 * Checks that the word cannot be used as a class/interface/trait name in your current php version.
 */
$cannotUseAsNamespaceName = $reservedWords->isReservedClassName($word);
/**
 * Checks that the word cannot be used as a function name in your current php version.
 */
$cannotUseAsFunctionName = $reservedWords->isReservedFunctionName($word);
/**
 * Checks that the word cannot be used as a method name in your current php version.
 */
$cannotUseAsMethodName = $reservedWords->isReservedMethodName($word);

/**
 * The following methods also accept a second parameter, to check against a PHP version different than your current runtime
 */
$cannotUseAsConstantName = $reservedWords->isReservedConstantName($word, '5.6');
$cannotUseAsNamespaceName = $reservedWords->isReservedNamespaceName($word, '5.6.1');
$cannotUseAsNamespaceName = $reservedWords->isReservedClassName($word, '5.6.1');
$cannotUseAsFunctionName = $reservedWords->isReservedFunctionName($word, '8.0');
$cannotUseAsMethodName = $reservedWords->isReservedMethodName($word, '7.4.2');