Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Self vs Static in PHP
<?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
You can’t perform that action at this time.