Skip to content

Instantly share code, notes, and snippets.

@stillfinder
Last active November 5, 2022 15:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stillfinder/8e88b25b7be85afaa431da00175c7a77 to your computer and use it in GitHub Desktop.
Save stillfinder/8e88b25b7be85afaa431da00175c7a77 to your computer and use it in GitHub Desktop.
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"
*/
@falahatiali
Copy link

selfVar is not a static function. how did you call it statically?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment