What is the difference between self and __CLASS__?

Asked

Viewed 86 times

0

Studying the Singleton design pattern, I was running some tests:

class Test {
    public static $var = "XYZ";
    static function class() {
        return __CLASS__;
    }
    static function self() {
        return self::$var;
    }
    static function compare() {
        return self === __CLASS__;
    }
}

echo Test::$var; //XYZ
echo Test::class()::$var; //XYZ
echo Test::self(); //XYZ
var_dump(Test::compare()); //bool(false)

I realized that self is used to access a variable or function within the class, and __CLASS__ returns the reference of the class itself

Am I right? Is that the only difference between the two? Are there any cases where either use one or the other? Why if I do it doesn’t work?

class Test {
    public static $var = "XYZ";
    static function class() {
        return __CLASS__::$var;
    }
    static function self() {
        return self;
    }
}

echo Test::class(); //syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ';'
echo Test::self()::$var; //Uncaught Error: Class 'self' not found
  • @Guilhermenascimento but the other question is about static and self this is about __CLASS__ and self, because they are duplicates?

  • dear Uilherme, the question yes, but the answers are quite complete, give a read please.

  • About the error T_PAAMAYIM_NEKUDOTAYIM: https://answall.com/q/77450/3635

  • 1

    ps: the downvote is not mine, only the closing vote. I find some dups useful to find good existing links ;) ... ps: I added 3 more useful links. I hope it helps, anything you think is missing you can put a reward on the existing questions, or if you think it’s something quite different you can edit this question here and explain what the other answers do not meet.

  • @Guilhermenascimento was worth the links, I will read

  • 1

    Dear William, the following is another link: https://answall.com/q/242625/3635

  • People should comment on their downvotes... I think it is wrong for a person to deny a question or an answer without opening a dialogue for both to share knowledge. Although the question is potentially duplicated, this would be no reason to downvote... in my view...

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.