Checking if a class is a subclass of another

2020-08-09 06:41发布

I want to check if a class is a subclass of another without creating an instance. I have a class that receives as a parameter a class name, and as a part of the validation process, I want to check if it's of a specific class family (to prevent security issues and such). Any good way of doing this?

5条回答
走好不送
2楼-- · 2020-08-09 06:57

is_subclass_of() will correctly check if a class extends another class, but will not return true if the two parameters are the same (is_subclass_of('Foo', 'Foo') will be false).

A simple equality check will add the functionality you require.

function is_class_a($a, $b)
{
    return $a == $b || is_subclass_of($a, $b);
}
查看更多
Deceive 欺骗
3楼-- · 2020-08-09 07:06

You can use is_a() with the third parameter $allow_string that has been added in PHP 5.3.9. It allows a string as first parameter which is treated as class name:

Example:

interface I {}
class A {}
class B {}
class C extends A implements I {}

var_dump(
    is_a('C', 'C', true),
    is_a('C', 'I', true),
    is_a('C', 'A', true),
    is_a('C', 'B', true)
);

Output:

bool(true)
bool(true)
bool(true)
bool(false)

Demo: http://3v4l.org/pGBkf

查看更多
对你真心纯属浪费
4楼-- · 2020-08-09 07:07

You need to use is_subclass_of() function to find that out. Please check below sample code.

class Foo{
 function __construct(){
  print("This is class Foo<br/>");
 }
}

class Bar extends Foo{
 function __construct(){
  print("This is class Bar<br/>");
 }
}

$f = new Foo();
$b = new Bar();

print("Is Bar Subclass of Foo : ".is_subclass_of($b,'Foo')."<br/>");
print(is_subclass_of($f,'Bar'));

-- The output for the same would be:

This is class Foo
This is class Bar
Is Bar Subclass of Foo : 1

Please note that no output will be printed for last line is_subclass_of($f,'Bar') which will make it fail in conditional checking.

If you want to see their boolean values, you need to use var_dump() instead of print() function.

Please check this link for more information

查看更多
相关推荐>>
5楼-- · 2020-08-09 07:11

Check out is_subclass_of(). As of PHP5, it accepts both parameters as strings.

You can also use instanceof, It will return true if the class or any of its descendants matches.

查看更多
劳资没心,怎么记你
6楼-- · 2020-08-09 07:12

Yup, with Reflection

<?php

class a{}

class b extends a{}

$r = new ReflectionClass( 'b' );

echo "class b "
    , (( $r->isSubclassOf( new ReflectionClass( 'a' ) ) ) ? "is" : "is not")
    , " a subclass of a";
查看更多
登录 后发表回答