Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a function is public or protected in PHP

Tags:

php

I am building an API where the user requests a 'command', which is passed into a class. Assuming the command matches a PUBLIC function, it will execute successfully. If the command matches a PROTECTED function, it needs to throw an error.

The idea is that functions can be disabled by changing them from PUBLIC to PROTECTED, rather than renaming them or removing them.

I currently do this, but it doesn't matter if the command is public or protected.

<?php /**  * Look for Command method  */ $sMethod = "{$sCommand}Command"; if (method_exists($this, $sMethod)) {     /**      * Run the command      */     return $this->$sMethod($aParameters); } 
like image 212
Stephen RC Avatar asked Nov 12 '10 01:11

Stephen RC


People also ask

What is a protected function PHP?

The protected keyword ensures that all properties/methods declared/defined using this keyword cannot be accessed externally. However, its main advantage over the "private" keyword is that such methods/properties can be inherited by child classes.

What is public function in PHP?

public - the property or method can be accessed from everywhere. This is default. 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 I access private function in PHP?

php //Accessing private method in php with parameter class Foo { private function validateCardNumber($number) { echo $number; } } $method = new ReflectionMethod('Foo', 'validateCardNumber'); $method->setAccessible(true); echo $method->invoke(new Foo(), '1234-1234-1234'); ?>

Are protected functions public?

The difference is as follows: Public :: A public variable or method can be accessed directly by any user of the class. Protected :: A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.


1 Answers

Simply use ReflectionMethod:

/**  * Look for Command method  */ if (method_exists($this, $sMethod)) {     $reflection = new ReflectionMethod($this, $sMethod);     if (!$reflection->isPublic()) {         throw new RuntimeException("The called method is not public.");     }     /**      * Run the command      */     return $this->$sMethod($aParameters); } 
like image 61
meze Avatar answered Sep 21 '22 17:09

meze