samcrosoft / constantaccess
这个库可以通过类似于数组或典型类对象的方式创建和读取(访问)常量,从而可以在不进行字符串连接的情况下在字符串中使用常量
dev-master
2015-11-28 15:55 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-18 18:33:40 UTC
README
constantaccess
这个库可以通过类似于数组或典型类对象的方式创建和读取(访问)常量,从而可以在不进行字符串连接的情况下在字符串中使用常量
示例
创建一个常量访问库的对象,然后开始创建或读取常量
$oConst = new Samcrosoft\ConstantAccess\ConstantAccess();
使用数组实例化常量类
您可以提供数组键=>值对以创建常量,注意:此数组应为一维数组
例如
$aData = array( 'const1' => 2, 'const2' => 22, '_const3' => 'another constant' ); // then create it now as $oConst = new Samcrosoft\ConstantAccess\ConstantAccess($aData);
使用对象方法或数组访问创建常量
$oConst->CONST1 = 23; This creates a constant called CONST1 $oConst['CONST2'] = "constant 2"; This creates another constant called CONST2
抛出异常
要创建有效的PHP常量,必须满足以下条件
- 常量键只能是一个有效的PHP变量名
- 常量值只能是一个标量类型的值
在创建常量之前,将执行上述测试,因此如果上述条件之一未遵守或满足,则可能会抛出异常
ConstantAccess 默认静默失败,即它不会抛出任何异常,但为了良好的编程实践,您应该处理所有可能的异常情况
启用异常
您可以通过两种方式启用异常:
- 在创建类对象时
- 通过使用 setThrowException 方法
例如
1 - $oConst = new Samcrosoft\ConstantAccess\ConstantAccess(array(), true); 2 - $oConst->setThrowException(false);
默认返回值
如果未定义常量,您可以配置默认返回值,在那种情况下返回该值而不是中断您的应用程序
e.g To set the default return value to null, you do the following $oConst->setValueReturnIfNotDefined(null); hence, $oConst->UNDEFINED; would return null
读取/访问常量
print "this is a trial message with {$oConst->CONST1} or another {$oConst->CONST2}";
测试
只需在放置库的文件夹中运行Phpunit
### 示例
示例位于 /examples 文件夹中