Skip to content

Instantly share code, notes, and snippets.

@DragonBe
Created November 22, 2013 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DragonBe/7597936 to your computer and use it in GitHub Desktop.
Save DragonBe/7597936 to your computer and use it in GitHub Desktop.
Accessing protected and private properties
<?php
class Nik
{
public $name;
protected $_function;
private $_age;
private function _getProperties()
{
$properties = array_keys(get_object_vars($this));
$list = array ();
foreach ($properties as $property) {
$clean = str_replace('_','', $property);
$list[$clean] = $property;
}
return $list;
}
public function __set($name, $value)
{
$names = $this->_getProperties();
if (in_array($name, array_keys($names))) {
$this->$names[$name] = $value;
}
}
public function __get($name)
{
$names = $this->_getProperties();
if (in_array($name, array_keys($names))) {
return $this->$names[$name];
}
}
public function toArray()
{
$self = $this;
return function() use ($self) {
return get_object_vars($self);
};
}
}
$nik = new Nik();
$nik->name = 'Nik';
$nik->function = 'Sr. Developer';
$nik->age = '32';
$result = $nik->toArray();
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment