PHP Can static:: replace self::?

后端 未结 2 701
一整个雨季
一整个雨季 2020-11-30 21:01

I am a little confused with this matter. I am designing an ORM class that tries to behave very similarly to ActiveRecord in ruby on rails, but that\'s beside the point.

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 21:13

    You have to ask yourself: "Am I targeting the problem with the adequated approach?"

    self:: and static:: do two different things. For instance self:: or __CLASS__ are references to the current class, so defined in certain scope it will NOT suffice the need of static calling on forward.

    What will happen on inheritance?

    class A {
        public static function className(){
            echo __CLASS__;
        }
    
        public static function test(){
            self::className();
        }
    }
    
    class B extends A{
        public static function className(){
            echo __CLASS__;
        }
    }
    
    B::test();
    

    This will print

    A
    

    In the other hand with static:: It has the expected behaviour

    class A {
        public static function className(){
            echo __CLASS__;
        }
    
        public static function test(){
            static::className();
        }
    }
    
    class B extends A{
        public static function className(){
            echo __CLASS__;
        }
    }
    
    
    B::test();
    

    This will print

    B
    

    That is called late static binding in PHP 5.3.0. It solves the limitation of calling the class that was referenced at runtime.

    With that in mind I think you can now see and solve the problem adequately. If you are inheriting several static members and need access to the parent and child members self:: will not suffice.

提交回复
热议问题