One minute
self vs. static
I get confused with self
and static
. Then I research and learn it. Then I forget it again. And so on.
TLDR
self
refers to the same class in which the new keyword is actually written.
static
, in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on.
By BoltClock on Stack Overflow
An example
<?php
class Foo
{
public function __invoke()
{
echo 'self: ' . self::class . PHP_EOL;
echo 'static: ' . static::class . PHP_EOL;
echo 'get_class(): ' . get_class() . PHP_EOL;
echo 'get_class($this): ' . get_class($this) . PHP_EOL;
echo 'get_called_class(): ' . get_called_class() . PHP_EOL;
}
}
class Bar extends Foo
{
}
(new Bar())();
Output
self: Foo
static: Bar
get_class(): Foo
get_class($this): Bar
get_called_class(): Bar
Test it on 3v4l.org.
See also
Read other posts