Home arrow PHP arrow Page 2 - Getting More Info on Reflected Properties with the Reflection API

Review: getting basic information about class properties with reflection - PHP

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.

TABLE OF CONTENTS:
  1. Getting More Info on Reflected Properties with the Reflection API
  2. Review: getting basic information about class properties with reflection
  3. Checking for a class property's existence with the hasProperty() reflection method
  4. Retrieving all of the static properties of a class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
March 22, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: