Row*_*wan 5 php oop static scope isset
我正在研究一个需要通过静态函数调用和对象方法访问的类.我发现的一件事是我在多个函数中复制逻辑.
简化示例:
class Configurable{
protected $configurations = array();
protected static $static_configurations = array();
public function configure($name, $value){
// ...lots of validation logic...
$this->configurations[$name] = $value;
}
public static function static_configure($name, $value){
// ...lots of validation logic (repeated)...
self::$static_configurations[$name] = $value;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经找到了解决方案,但感觉非常脏:
class Configurable{
protected $configurations = array();
protected static $static_configurations = array();
public function configure($name, $value){
// ...lots of validation logic...
if (isset($this)){
$this->configurations[$name] = $value;
}
else{
self::$static_configurations[$name] = $value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我也需要静态功能,以便我可以在整个应用程序中设置配置.此外,这种技术的好处是我可以在两个范围中使用相同的方法名称.
这样的测试范围有问题吗?性能问题,前向兼容性问题等.它在PHP 5.2上都适用于我,我不需要支持<5.
第二种方法的问题是,当错误报告设置为 时,会导致错误E_STRICT。例如:
严格标准:非静态方法 Foo::bar() 不应在 /home/yacoby/dev/php/test.php 第 10 行静态调用
PHP6 的一个要点是 E_STRICT 错误已移至 E_ALL。换句话说,E_ALL 将覆盖所有错误,包括不允许您静态调用非静态方法。
另一种方法可能是将验证逻辑移至静态函数。这样非静态函数和静态函数就可以调用验证逻辑。