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
andself
this is about__CLASS__
andself
, because they are duplicates?– Costamilam
dear Uilherme, the question yes, but the answers are quite complete, give a read please.
– Guilherme Nascimento
About the error
T_PAAMAYIM_NEKUDOTAYIM
: https://answall.com/q/77450/3635– Guilherme Nascimento
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.
– Guilherme Nascimento
@Guilhermenascimento was worth the links, I will read
– Costamilam
Dear William, the following is another link: https://answall.com/q/242625/3635
– Guilherme Nascimento
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...
– Andrei Coelho