0
votes

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, e.g. :

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)

2

2 Answers

1
votes

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

0
votes

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