Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a class property is private or protected

Tags:

oop

php

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?

like image 735
Shoe Avatar asked Dec 13 '22 07:12

Shoe


1 Answers

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());
?>
like image 120
Alex Turpin Avatar answered Jan 20 '23 10:01

Alex Turpin