detect protected method and avoid fatal error
I have to get properties from multiple classes stored in one directory.
I have no problems collecting protected and public properties.
I'm after public only, so all's fine up to now.
What I do:
$foo = new Foo(); $reflect = new ReflectionClass($foo); $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); foreach ($props as $prop) { print $prop->getName() . "n"; }
However, some classes do have protected methods, eg :
class Foo { public $foo = 1; protected $bar = 2; private $baz = 3; protected function __construct() { } }
Once I hit such a class, I get a fatal error, which stalls mys efforts:
Fatal error: Call to protected Foo::__construct() from context 'View' in [path/goes/here]
What is the best way around it? (if there is one)
Change
$foo = new Foo();
$reflect = new ReflectionClass($foo);
to
$reflect = new ReflectionClass('Foo');
If you actually want to create a new instance, look at the newInstanceWithoutConstructor
function
If you use protected
or private
then your constructor will not be accessible from outside of the class.
Calling $foo = new Foo();
will throw an error.
$reflect = new ReflectionClass('Foo');
echo $reflect->getName();// output Foo
链接地址: http://www.djcxy.com/p/60258.html
上一篇: OOP和私人领域的继承
下一篇: 检测受保护的方法并避免致命错误