PHP

Get Certain Properties of a Class in PHP

Using the below code you can get the public and protected variables of a class. WARNING: do not use this in a loop. If you need to set class variables through predefined variables please use this function outside of a loop, store the results and then foreach it:

  	public function populate($user = Array()){
  		
  		$props = $this->listProperties();
  		
  		foreach($user as $k => $v){
  			if(array_key_exists($k, $props)){
  				$this->{$k} = $v;
  			}
  		}
  	}

This is because this function (to find class variables) is slow and I have discovered PHP will run this function everytime even in a foreach loop which will considerably reduce speed after a random amount of time.

The function for getting class variables is:

        $reflect = new ReflectionClass(get_class($this));
          foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PROTECTED) as $prop) {
              $arr[$prop->getName()] = $this->{$prop->getName()};
          }

When getting a class you can use either a name or an object. To use an object do: new ReflectionObject($this). To use the class constant use: new ReflectionClass(__CLASS__). And there you have the properties of a class in php.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s