get_class() 的作用是返回对象的类名。
说明
用法:
string get_class ([ object $obj ] )
返回 obj 对象对应的类名,如果 obj 不是对象,则会返回 false。
通过这个方法,我们在写一些底层相关的代码的时候,可以轻松很多。
立即学习“PHP免费学习笔记(深入)”;
注意:自 PHP 5 起,如果在对象的方法中调用则 obj 为可选项。
实例
实例1:
<?phpclass TestCase{ function getName()
{ echo "My name is ", get_class($this), "\n";
}
}// Create an object
$instance = new TestCase();
// External call
echo "Its name is ", get_class($instance), "\n";
// Internal call
$instance->getName();输出结果为:Its name is TestCase My name is TestCase
实例2:带命名空间的类
<?php
namespace TestNamespace;
class TestCase{
function getName()
{
echo "My name is ", get_class($this), "\n";
}
}
// Create an object
$instance = new TestCase();
// External call
echo "Its name is ", get_class($instance), "\n";
// Internal call
$instance->getName();输出结果为:Its name is TestNamespace\TestCase My name is TestNamespace\TestCase
因此,若要获得这个类对应的命名空间,这个方法也是超有用的。
实例3:忽略obj参数
<?phpnamespace TestNamespace;class TestParentCase{ function getName()
{ echo "My name is ", get_class(), "\n";
}
}class TestCase extends TestParentCase{ function getThisName()
{ echo "My name is ", get_class(), "\n";
}
}// Create an object$instance = new TestCase();
$instance->getName();
$instance->getThisName();输出结果为:My name is TestNamespace\TestParentCase My name is TestNamespace\TestCase
注意返回的结果中的差异,省略obj参数以后,获取到的是定义它的类的名称
有其它需要注意的情况,欢迎大家向 Hy369 反馈,我会及时补充到自己的博客中的。
以上就是笔记016 PHP中的 get_class() 函数的内容,更多相关内容请关注PHP中文网(www.php.cn)!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号