Home arrow PHP arrow Page 2 - Working with Reflected Properties with the Reflection API

Review: working with reflected methods - PHP

In this fourth part of a seven-part series, I demonstrate how to use the PHP reflection API to retrieve useful information about the properties declared by a specific class. Reflection allows you to do more with properties of a class than determine their visibility or learn the values assigned to them, but that's what we'll be covering here.

TABLE OF CONTENTS:
  1. Working with Reflected Properties with the Reflection API
  2. Review: working with reflected methods
  3. Manipulating properties of a reflected class
  4. Getting all the properties of the User class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
March 15, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

In case you haven’t yet read the previous part of the series, where I discussed how to use the power of reflection to get relevant information about the methods defined by a sample class, below I reintroduced the definition of this class and the interfaces that it implements.

Take a close look at these sample structures:

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;

    }         

}

 

Obviously, in this case the “Identifier” interface and its implementing class have been coded only for demonstration purposes, since they do nothing particularly useful. Things become more interesting, though, when the methods of this sample class are inspected through reflection. That’s exactly what the following script does, so pay attention to it, please: 

// 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 a ReflectionMethod object

$method = $reflector->getMethod('getFirstName');

 

 

 

// check to see if the reflected method is public, protected or private

if ($method->isPublic())

{

    echo 'The method is public'; // displays 'The method is public'

   // invoke the reflected method

   echo $method->invoke($user); // displays 'Alejandro'   

}

elseif ($method->isProtected())

{

    echo 'The method is protected';

}

elseif ($method->isPrivate())

{

    echo 'The method is private';

}

elseif ($method->isStatic())

{

    echo 'The method is static';

}

 

 

 

// get all public methods of reflected class

print_r($reflector->getMethods(ReflectionMethod::IS_PUBLIC)); // displays Array ( [0] => ReflectionMethod Object ( [name] => __construct [class] => User ) [1] => ReflectionMethod Object ( [name] => setId [class] => User ) [2] => ReflectionMethod Object ( [name] => getId [class] => User ) [3] => ReflectionMethod Object ( [name] => setFirstName [class] => User ) [4] => ReflectionMethod Object ( [name] => getFirstName [class] => User ) [5] => ReflectionMethod Object ( [name] => setLastName [class] => User ) [6] => ReflectionMethod Object ( [name] => getLastName [class] => User ) [7] => ReflectionMethod Object ( [name] => setEmail [class] => User ) [8] => ReflectionMethod Object ( [name] => getEmail [class] => User ) )

 

As you can see above, determining the level of visibility assigned to one or more methods of the pertinent “User” class, or directly invoking them from client code, is only a matter of calling the proper methods provided by the reflection API and nothing else. In addition, the last line of the previous script also shows how to get all of the public methods defined by “User,” which is accomplished by passing the “IS_PUBLIC” constant defined by the built-in ReflectionMethod class to the “getMethods()” method.

So far, so good. Now that you've learned how to easily manipulate methods of a class via reflection, it’s time to explore other methods of the API. Thus, in keeping with the concepts just deployed in the introduction, in the segment to come I’m going to discuss how to take advantage of reflection for retrieving useful information about the properties declared by the previous “User” class.

To learn more about this brand new process, click on the link below and read the following section.



 
 
>>> 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: