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); }
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.
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.
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'); ?>
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.
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); }
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