Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
//
//class ParentClass
//{
// public function getClassName()
// {
// return get_called_class() === (new \ReflectionMethod(get_called_class(), __FUNCTION__))->getDeclaringClass()->getName();
// }
//
// public function getClassNameDoesntExist()
// {
// return get_called_class() === (new \ReflectionMethod(get_called_class(), __FUNCTION__))->getDeclaringClass()->getName();
// }
//}
//
//class ChildClass extends ParentClass
//{
// public function getClassName()
// {
// return get_called_class() === (new \ReflectionMethod(get_called_class(), __FUNCTION__))->getDeclaringClass()->getName();
// }
//
// public function parent_getClassName()
// {
// return parent::getClassName();
// }
//}
//
//$child = new ChildClass();
//
//
//var_dump(
// $child->getClassName() ,//=== 'ChildClass',
// $child->getClassNameDoesntExist() ,//=== 'ChildClass',
// $child->parent_getClassName() ,//=== 'ParentClass'
//''
//);
class ParentClass
{
public function get_called_class($method)
{
$get_called_class = get_called_class();
list($get_class, $function) = explode('::', $method);
return ($get_called_class === $get_class || (new \ReflectionMethod($get_called_class, $function))->getDeclaringClass()->getName() === $get_called_class) ? $get_class : $get_called_class;
}
public function getClassName()
{
return $this->get_called_class(__METHOD__);
}
public function getClassNameDoesntExist()
{
return $this->get_called_class(__METHOD__);
}
}
class ChildClass extends ParentClass
{
public function getClassName()
{
return $this->get_called_class(__METHOD__);
}
public function parent_getClassName()
{
return parent::getClassName();
}
}
$child = new ChildClass();
var_dump(
$child->getClassName() ,
$child->getClassNameDoesntExist(),
$child->parent_getClassName()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment