Getting More Info on Reflected Properties with the Reflection API

In this fifth part of the series you will learn a couple of additional methods included with the PHP reflection API. The first one will allow you to check the existence of a specified class property, and the second one will permit you to retrieve all of the static properties defined by that class at once.

Frankly speaking, the powerful reflection library that comes included with PHP 5 is one of those features that you, as a web developer, can’t live without once you’ve discovered its real functionality. While is fair to say that in the old days of PHP 4, the language already provided some native functions that allowed developers to achieve a decent level of introspection in classes and objects, the reflection API permits you to analyze the internal structure of classes and interfaces by using an intuitive object-oriented approach, or expressed in other words, you can use reflective classes that inspect other classes. What else can you ask for?

Well, feature-hungry programmers (and that includes myself, of course) will always ask for more. In its current version, however, the reflection API will let you perform a thorough reverse engineering process on your own classes, such as knowing what methods and properties they define, the level of visibility assigned to those members, and even instantiate directly classes from client code without having to explicitly write any “new” constructs.

Naturally, if you’ve been a loyal follower of this series and already went through all of the articles that precede this one, then you’re already familiar with using some of the most important methods included with the reflection API. In those tutorials I coded a few simple examples that showed, for instance, how to get all of the methods declared by a class and how to determine if the methods in question were public, protected or private.

Also, I left off the last installment discussing how to retrieve all of the properties declared by the aforementioned class, along with their level of visibility, which was a straightforward process. Of course, as you might have guessed, the ability to manipulate class properties via reflection doesn’t stop here. To prove this, in the lines to come I’m going to demonstrate how to determine if a specified property exists within a class, and whether or not the class defines any static properties.

So, now that you know what to expect from this part of the series, it’s time to explore a few more handy methods bundled with the PHP reflection API. Let’s jump in!

{mospagebreak title=Review: getting basic information about class properties with reflection}

As usual, before I demonstrate how to use reflection to determine if a specified property has been declared by a class and how to get all of its static properties (when applicable), I would first like to spend a few moments reintroducing the examples developed in the previous chapter of the series. They showed how to retrieve basic information on the properties of a basic user class.

First, here’s the definition of that example class, along with its associated interface. Check them out:

interface Identifier

{

    public function setId($id);

   

    public function getId();

    

}

 

 

/**

* A sample user class

*

* @param  id fname lname email

*/

class User implements Identifier

{

    private $id = NULL;

    private $fname = ‘Alejandro';

    private $lname = ‘Gervasio';

    private $email = ‘alejandro@domain.com';

    const HEADING = ‘Using the Reflection API in PHP 5′;

   

    // constructor (not implemented)

    public function __construct(){}

   

    //setter for id property

    public function setId($id)

    {

        if (!is_numeric($id))

        {

            throw new Exception(‘ID must be a numeric value’);

        }

        $this->id = $id;

    }

   

    // getter for id property

    public function getId()

    {

        return $this->id;

    }

       

    // setter for fname property

    public function setFirstName($fname)

    {

        if (empty($fname) OR !is_string($fname))

        {

            throw new Exception(‘First name must be a non-empty string.’);

        }

        $this->fname = $fname;

    }

   

    // getter for fname property

    public function getFirstName()

    {

        return $this->fname;

    }

   

    // setter for lname property

    public function setLastName($lname)

    {

        if (empty($fname) OR !is_string($fname))

        {

            throw new Exception(‘Last name must be a non-empty string.’);

        }

        $this->lname = $lname; 

    }

   

    // getter for lname property

    public function getLastName()

    {

        return $this->lname;

    }

   

    // setter for email property

    public function setEmail($email)

    {

        if (empty($email) OR !is_string($email) OR strpos($email, ‘@’) === FALSE)

        {

            throw new Exception(‘Email must be a well-formatted email address.’);

        }

        $this->email = $email; 

    }

   

    // getter for email property

    public function getEmail()

    {

        return $this->email;

    }         

}

For the sake of completeness, I included the definitions of the above “Identifier” interface and its implementing “User” class. Taking into consideration that the source code speaks for itself, I’m not going to waste your time (and mine) explaining how these structures work. Instead, you should pay attention to the following code fragment. It shows how to determine the level of visibility assigned to each property of the previous “User” class, and how to get those properties via a single method call.

Here’s the script that performs these specific tasks:

// create instance of ‘User’ class

$user = new User();

 

 

// create instance of Reflection class and pass in ‘User’ class as argument

 

 

$reflector = new ReflectionClass(‘User’);

 

 

// check the visibility of retrieved properties

foreach ($reflector->getProperties() as $property)

{

    if ($property->isPublic())

    {

        echo ‘Property : ‘ . $property->getName() . ‘ is public<br />';

    }

    elseif ($property->isProtected())

    {

        echo ‘Property : ‘ . $property->getName() . ‘ is protected<br />';

    }

    elseif ($property->isPrivate())

    {

        echo ‘Property : ‘ . $property->getName() . ‘ is private<br />';

    }

    /*displays the following

    Property : fname is private

    Property : lname is private

    Property : email is private

    */

}

 

 

// get all the properties of reflected class

print_r($reflector->getProperties()); // displays Array ( [0] => ReflectionProperty Object ( [name] => id [class] => User ) [1] => ReflectionProperty Object ( [name] => fname [class] => User ) [2] => ReflectionProperty Object ( [name] => lname [class] => User ) [3] => ReflectionProperty Object ( [name] => email [class] => User ) )

From the earlier example, it’s clear to see that retrieving via reflection basic information about the properties declared by a specified class is a simple process. As mentioned at the beginning of this article though, the reflection API will let you inspect those properties more deeply, which will allow you to find out, for instance, whether or not a specific property has been defined by a class.

Logically, this capability can be easily applied to each property of the familiar “User” class as well. Therefore, in the following section I’m going to write an example that will show how to accomplish this task in a very simple manner.

Now, click on the link that appears below and keep reading.

{mospagebreak title=Checking for a class property’s existence with the hasProperty() reflection method}

Among the plethora of methods that come with the reflection API, there’s one called “hasProperty().” As its name suggests, it can be used for verifying the existence of a specified property within a class. This method takes the name of the property to be inspected as an incoming argument, and an example of its usage is shown below:

// create instance of ‘User’ class

$user = new User();

 

 

// create instance of Reflection class and pass in ‘User’ class as argument

 

 

$reflector = new ReflectionClass(‘User’);

 

 

// check if the reflected class has a specified property

if ($reflector->hasProperty(‘lname’))

{

    echo ‘Property found in reflected class'; // displays ‘Property found in reflected class’

}

else

{

    echo ‘Property not found in reflected class';

}

As you can see in the above code fragment, the “hasProperty()” method can be really helpful for checking the existence of a given class property. In this case, the property being checked within the “User” class is “lname,” but of course it’s possible to inspect others with the same ease.

Now that you’ve surely learned how to utilize one method of the reflection API to know if a class declares a specified property, it’s time to explore a few others. In consonance with this premise, in the last segment of this tutorial I’m going to explain how to get all of the static properties defined by the sample “User” class.

Want to see how this will be done? Then click on the link below and read the following section.

{mospagebreak title=Retrieving all of the static properties of a class}

If all of the methods covered previously weren’t good enough, the reflection API also provides an additional one called “getStaticProperties()” that allows you to collect all of the static properties defined by a class. The result is returned to client code as an associative array, which can be easily traversed via a “foreach” construct.

Unfortunately, the “User” class that I’m using here for testing purposes doesn’t declare any static properties. Despite this issue, the following code sample should give you a clear idea of how to use this method in a concrete case:   

// create instance of ‘User’ class

$user = new User();

 

 

// create instance of Reflection class and pass in ‘User’ class as argument

 

 

$reflector = new ReflectionClass(‘User’);

 

 

// get static properties of reflected class

print_r($reflector->getStaticProperties()); // displays nothing

That was pretty easy to accomplish, wasn’t it? As it was done previously with instance-level methods and properties, the “getStaticProperties()” method returns an array containing all of the static properties of a class. In the above code sample, for the reason mentioned before, the method simply will return an empty array. However, the example is more than enough to demonstrate the real functionality of this reflection method.

And with this last example, we’ve come to the end of this article. As always, feel free to edit all of the code samples included in this tutorial, which surely will improve your skill in using the PHP reflection API.     

Final thoughts

That’s all for the moment. In this firth episode of the series you learned a couple of additional methods included with the PHP reflection API. The first one allowed you to check the existence of a specified class property, and the second one permitted you to retrieve all of the static properties defined by that class. Of course, in the case of “User,” the latter task is rather pointless, as it declares no static properties, but in other situations it might be pretty useful.

In the next tutorial I’m going to explain how to use the power of reflection to determine if a class is an implementer of a given interface, and if it’s been defined abstract and final as well.

Don’t miss the upcoming article!

[gp-comments width="770" linklove="off" ]

chat