Shoe
Shoe

Reputation: 76280

How to detect if a class property is private or protected

How can I detect if a class property is private or protected without using external libraries (pure PHP only)? How can I check if I can set the property from outside the class or I cannot?

Upvotes: 4

Views: 2888

Answers (3)

Alex Turpin
Alex Turpin

Reputation: 47776

Use Reflection.

<?php
    class Test {
        private $foo;
        public $bar;
    }

    $reflector = new ReflectionClass(get_class(new Test()));

    $prop = $reflector->getProperty('foo');
    var_dump($prop->isPrivate());

    $prop = $reflector->getProperty('bar');
    var_dump($prop->isPrivate());
?>

Upvotes: 8

Nonym
Nonym

Reputation: 6299

Use:

print_r($object_or_class_name);

It should draw it out for you, properties that you can or can't access..

For example:

class tempclass {
    private $priv1 = 1;
    protected $prot1 = 2;
    public $pub1 = 3;

}
$tmp = new tempclass();
print_r($tmp);
exit;

Just to illustrate that I have one private property, one protected property, and one public property. Then we see the output of print_r($tmp);:

tempclass Object
(
    [priv1:tempclass:private] => 1
    [prot1:protected] => 2
    [pub1] => 3
)

Or am I misunderstanding your post? Haha

Upvotes: 0

Related Questions