Last active
November 5, 2022 15:21
-
-
Save stillfinder/8e88b25b7be85afaa431da00175c7a77 to your computer and use it in GitHub Desktop.
Self vs Static in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Animal | |
{ | |
public static $name = "animal"; | |
// Return the class that is represented by "self::" | |
public function getSelfClass() | |
{ | |
return get_class(); | |
} | |
// Return the class that is represented by "static::" | |
public function getStaticClass() | |
{ | |
return get_called_class(); | |
} | |
public function selfVar() | |
{ | |
return self::$name; | |
} | |
public function staticVar() | |
{ | |
return static::$name; | |
} | |
public function selfMethod() | |
{ | |
return self::getName(); | |
} | |
public function staticMethod() | |
{ | |
return static::getName(); | |
} | |
protected function getName() | |
{ | |
return "animal"; | |
} | |
} | |
class Penguin extends Animal | |
{ | |
public static $name = "penguin"; | |
protected function getName() | |
{ | |
return "penguin"; | |
} | |
} | |
var_dump(Penguin::selfVar()); // animal | |
var_dump(Penguin::staticVar()); // penguin | |
var_dump(Penguin::selfMethod()); // animal | |
var_dump(Penguin::staticMethod()); // penguin | |
var_dump(Penguin::getSelfClass()); // Animal | |
var_dump(Penguin::getStaticClass()); // Penguin | |
/* | |
string(6) "animal" | |
string(7) "penguin" | |
string(6) "animal" | |
string(7) "penguin" | |
string(6) "Animal" | |
string(7) "Penguin" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
selfVar is not a static function. how did you call it statically?