PHP isset($ this)并在静态和对象上下文中使用相同的对象方法 [英] PHP isset($this) and using the same object method in a static and object context

查看:113
本文介绍了PHP isset($ this)并在静态和对象上下文中使用相同的对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个需要通过静态函数调用以及对象方法进行访问的类.我发现的一件事是我正在跨多个功能复制逻辑.

I'm working on a class which needs to be accessible via static function calls as well as object methods. One thing I have found is that I'm duplicating logic across multiple functions.

简化示例:

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;

        }

    }

我找到了解决方案,但感觉确实很脏:

I've found a solution to this, but it feels really dirty:

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;
            }

        }

    }

我还需要静态功能,以便可以在整个应用程序中设置配置.另外,使用此技术的好处是,我可以在两个范围中使用相同的方法名称.

I need the static function as well so that I can set configurations throughout the application. Also, the nice thing with this technique is that I can use the same method names in both scopes.

这样的测试范围是否存在任何问题?性能问题,前向兼容性问题等.所有这些都对我适用于PHP 5.2,并且我不需要支持< 5.

Are there any problems with testing scope like this? Performance issues, forward compatibility issues, etc. It all works for me on PHP 5.2, and I don't need to support <5.

推荐答案

第二种方法的问题在于,将错误报告设置为E_STRICT时,它将导致错误.例如:

The issue with the second method is that it will result in an error when error reporting is set to E_STRICT. For example:

严格的标准:非静态方法Foo :: bar()不应在第10行的/home/yacoby/dev/php/test.php中静态调用

Strict standards: Non-static method Foo::bar() should not be called statically in /home/yacoby/dev/php/test.php on line 10

PHP6的一点是E_STRICT错误已移至E_ALL.换句话说,E_ALL将涵盖所有错误,包括不允许您静态调用非静态方法.

A point with PHP6 is that the E_STRICT errors are moved to E_ALL. In other words E_ALL will cover all errors including not allowing you to call non static methods statically.

另一种方法可能是将验证逻辑移至静态函数.这样,非静态函数和静态函数可以调用验证逻辑.

An alternative method may be to move the validation logic to a static function. That way the non static function and the static function can call the validation logic.

这篇关于PHP isset($ this)并在静态和对象上下文中使用相同的对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆