Created
November 22, 2013 10:39
-
-
Save DragonBe/7597936 to your computer and use it in GitHub Desktop.
Accessing protected and private properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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