3

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

?> 

1 Answer 1

0

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
        )

)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It's odd that checking functions can be done with simple php functions but properties need to use the reflection class!
@Joe <pre> function isPublic($property, $object) { $r_object = new ReflectionObject($object); $properties = $r_object->getProperties(ReflectionProperty::IS_PUBLIC); if (is_array($properties) && count($properties) >0) { foreach ($properties as $ppt) { if ($ppt->name == $property) { return true; } } } return false; } </pre>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.