Reputation:
I have a class like this :
I would like to know what the differences between following commands, which one is better?
Class foo
{
function test()
{
return false;
}
function test2()
{
return self::test();
}
function test3()
{
return foo::test();
}
static function test4()
{
return false;
}
function test5()
{
return self::test4();
}
function test6()
{
return static::test4();
}
}
1 - Whats is a different between self::test();
and foo::test();
?
2 - Whats is a different between self::test4();
and static::test4();
?
Please explain??
Upvotes: 2
Views: 234
Reputation: 173552
function test2()
{
return self::test();
}
function test3()
{
return foo::test();
}
They both work in the same way, but when you want to rename your class; self
would still point to the correct class, but foo
would have to be renamed.
Even better would be to use $this->test()
.
function test5()
{
return self::test4();
}
function test6()
{
return static::test4();
}
The latter applies "late static binding" and so there will be a difference when this class is extended, e.g.:
class bar extends foo
{
function test4() { return true; }
}
$b = new bar;
Then when $b->test6()
is called it will return true
.
Upvotes: 0
Reputation: 160833
1 - Whats is a different between self::test(); and foo::test(); ?
It's the same, if used inside the class scope, self::
will be better, you don't have to change the code when you change the class name.
2 - Whats is a different between self::test4(); and static::test4(); ?
static::test4()
is implemented from php 5.3 as the Late Static Bindings feather, which can be used to reference the called class in a context of static inheritance.
Upvotes: 3
Reputation: 154
simply: self - is referencing the class you are in. while class_name could call a class method's outside of the class itself.
i.e - when you want to call test6 outside of 'foo' - you can't call it by 'self', you have to call it by 'foo::'.
which one is better?
As I explained. when writing inside the class it self, use 'self' - it's just 'best practice'.
Upvotes: 1