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.
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.
PHP has three visibility keywords - public, private and protected. A class member declared with public keyword is accessible from anywhare.
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.
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!"
You can use the reflection extension for that, consider these:
ReflectionMethod::isPrivate
ReflectionMethod::isProtected
ReflectionMethod::isPublic
ReflectionMethod::isStatic
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With