Home  >  Article  >  Backend Development  >  php反射api的一个小问题

php反射api的一个小问题

WBOY
WBOYOriginal
2016-06-06 20:16:261105browse

手册上写php反射api中ReflectionClass的isSubClass方法接收的参数是一个字符串类型,但是为什么传递ReflectionClass对象进去,功能也是可以实现的?

<code>class test1 {
    public $a;
}
class test1 extends test{
    public $b;
}
$object1 = new ReflectionClass('test1');
$object2 = new ReflectionClass('test2');
var_dump($object2 -> isSubclassOf($object2));
var_dump($object2 -> isSubclassOf('test1'));</code>

这两种输出都是boolean true,需要的参数是字符串,但是传递对象参数也是可行的,这是为什么?

回复内容:

手册上写php反射api中ReflectionClass的isSubClass方法接收的参数是一个字符串类型,但是为什么传递ReflectionClass对象进去,功能也是可以实现的?

<code>class test1 {
    public $a;
}
class test1 extends test{
    public $b;
}
$object1 = new ReflectionClass('test1');
$object2 = new ReflectionClass('test2');
var_dump($object2 -> isSubclassOf($object2));
var_dump($object2 -> isSubclassOf('test1'));</code>

这两种输出都是boolean true,需要的参数是字符串,但是传递对象参数也是可行的,这是为什么?

因为在php的源代码中这里是可以传入两种类型,第一是string第二是reflectionclass。
github上的地址:github

代码中很清楚的可以看到注释中写明

<code>/* {{{ proto public bool ReflectionClass::isSubclassOf(string|ReflectionClass class)
   Returns whether this class is a subclass of another class */
</code>

并且在接下来的switch语句中也进行了判断

<code>switch (Z_TYPE_P(class_name)) {
        case IS_STRING:
            //some code
        case IS_OBJECT:
            //some code
        default:
            //some code
    }</code>

php的外部维护者很多,所以文档不是很详细也是正常的,很多东西都需要自己去试。

大概手册没写全。
is_subclass_of估计是参照这个函数,这个手册说了可以传递对象。

这就算是php的一些漏洞(也算是优势,毕竟灵灵活)。
推荐按照手册上传参数,因为这些小漏洞的话会在后续版本修补掉的。
或者你可以去看下php手册的英文文档,那个比中文文档权威

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn