Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

PHP Can static:: replace self::?

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.

What I'm trying to say is that my class makes extensive use of static attribute inheritance, specially for database and table handling. My question is, should I use self:: at all?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...