Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some code snippets demonstrating mixing of static and non-static contexts in PHP
<?php
class Foo {
public static function bar() {
echo "calling public static bar() in an ".(isset($this)?"object (".get_class($this).")":"static")." context. \n";
}
public function baum() {
echo "calling public baum in an ".(isset($this)?"object (".get_class($this).")":"static")." context. \n";
}
}
class Thief {
public function meow() {
Foo::bar();
Foo::baum();
}
}
$foo=new Foo;
$t=new Thief;
echo "[0]\n";
Foo::bar();
echo "[1]\n";
$foo->bar();
echo "[2]\n";
Foo::baum();
echo "[3]\n";
$foo->baum();
echo "[4]\n";
Thief::meow();
echo "[5]\n";
$t->meow();
//$t->Foo::baum();
/*
This would create the most famous PHP error message:
PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /home/amoebe/static.php on line 37
*/
//call_user_func(array($t,'Foo::baum'));
/*
This fails too:
PHP Warning: call_user_func() expects parameter 1 to be a valid callback, class 'Thief' is not a subclass of 'Foo' in /home/amoebe/static.php on line 42
*/
/*
Output:
[0]
calling public static bar() in an static context.
[1]
calling public static bar() in an static context.
[2]
calling public baum in an static contiext.
[3]
calling public baum in an object (Foo) context.
[4]
calling public static bar() in an static context.
calling public baum in an static context.
[5]
calling public static bar() in an static context.
calling public baum in an object (Thief) context.
*/
?>
One oddity in PHP is that you can call static methods like
non-static and the other way around.
The only differnce is: When calling a method explicitly
declared as static you will be in a static context even
if the call looks like $object->method(), see [1].
Another surprising behaviour is calling foreign methods
in an non-static context, but with the static syntax, like
OtherClass::otherMethod() in $classInstance->method().
They will actually be called like own methods even having
the current obejct as $this availible,
see [5].
Reasonably, you can access $this, but not private/protected
properties in the foreign class. And you can't summon this
magic form outside the object's methods.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.