Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking method visibility in PHP

Is there any way of checking if a class method has been declared as private or public?

I'm working on a controller where the url is mapped to methods in the class, and I only want to trigger the methods if they are defined as public.

like image 492
phobia Avatar asked Jun 05 '10 18:06

phobia


People also ask

What is PHP visibility?

Visibility ¶ The visibility of a property, a method or (as of PHP 7.1. 0) a constant can be defined by prefixing the declaration with the keywords public , protected or private . Class members declared public can be accessed everywhere.

What are the different visibility is of method property?

PHP has three visibility keywords - public, private and protected. A class member declared with public keyword is accessible from anywhare.

What is a protected function PHP?

protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.

How can we access private members of a class in PHP?

php use PhpPrivateAccess\MyClass; $class = new MyClass(); // Create a closure from a callable and bind it to MyClass. $closure = \Closure::bind(function (MyClass $class) { return $class->property; }, null, MyClass::class); var_dump($closure($class)); // => string(11) "Im private!"


2 Answers

You can use the reflection extension for that, consider these:

ReflectionMethod::isPrivate
ReflectionMethod::isProtected
ReflectionMethod::isPublic
ReflectionMethod::isStatic

like image 174
Sarfraz Avatar answered Oct 12 '22 23:10

Sarfraz


To extend Safraz Ahmed's answer (since Reflection lacks documentation) this is a quick example:

class foo {
    private function bar() {
        echo "bar";
    }
}

$check = new ReflectionMethod('foo', 'bar');

echo $check->isPrivate();
like image 20
Matteo Riva Avatar answered Oct 12 '22 23:10

Matteo Riva