Reputation: 105
With classes containing private properties the property_exists() function returns true (php>5.3). With functions there is a method of is_callable that confirms not only the method exists but it is also available (as an alternative to method_exists()). Is there an equivalent counterpart to this function that will confirm if this property is accessible?
<?php
class testClass {
private $locked;
public $unlocked;
private function hiddenFunction(){
return "hidden";
}
public function visibleFunction(){
return "visible";
}
}
$object = new testClass();
var_dump(property_exists($object, "unlocked")); // returns true
var_dump(property_exists($object, "locked")); // returns true > php 5.3
var_dump(method_exists($object, "hiddenFunction")); // returns true but can't be called
var_dump(method_exists($object, "visibleFunction")); // returns true
var_dump(is_callable(array($object, "hiddenFunction"))); // returns false
var_dump(is_callable(array($object, "visibleFunction"))); // returns true
?>
Upvotes: 3
Views: 2088
Reputation: 7795
You can use Reflection class taht will let you reverse-engineer classes, interfaces, functions, methods and extensions.
For example, to get all public properties of a class, you can do as follow :
$reflectionObject = new ReflectionObject($object);
$testClassProperties = $reflectionObject->getProperties(ReflectionProperty::IS_PUBLIC);
print_r ($testClassProperties);
OUTPUT
Array
(
[0] => ReflectionProperty Object
(
[name] => unlocked
[class] => testClass
)
)
to get all public methods of a class, you can do as follow :
$reflectionObject = new ReflectionObject($object);
$testClassProperties = $reflectionObject->getMethods(ReflectionProperty::IS_PUBLIC);
print_r ($testClassProperties);
OUTPUT
Array
(
[0] => ReflectionMethod Object
(
[name] => visibleFunction
[class] => testClass
)
)
Upvotes: 0