Last active
August 29, 2015 13:55
-
-
Save evillemez/8735382 to your computer and use it in GitHub Desktop.
traits, magic methods and inheritance
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 | |
trait Methods | |
{ | |
public function __call($name, $args) | |
{ | |
if (property_exists($this, $name)) { | |
return $this->$name; | |
} | |
if (($parent = get_parent_class(__CLASS__)) && method_exists($parent, '__call')) { | |
return parent::__call($name, $args); | |
} | |
throw new RuntimeException("Computer says no."); | |
} | |
} | |
class Person | |
{ | |
use Methods; | |
private $pPrivate = 'pPrivate'; | |
protected $pProtected = 'pProtected'; | |
public $pPublic = 'pPublic'; | |
} | |
class Salesman extends Person | |
{ | |
use Methods; | |
private $sPrivate = 'sPrivate'; | |
protected $sProtected = 'sProtected'; | |
public $sPublic = 'sPublic'; | |
} | |
class Zombie | |
{ | |
private $zPrivate = 'zPrivate'; | |
protected $zProtected = 'zProtected'; | |
public $zPublic = 'zPublic'; | |
} | |
class Walker extends Zombie | |
{ | |
use Methods; | |
} | |
$dude = new Salesman(); | |
//inheritance | |
var_dump($dude->sPublic()); | |
var_dump($dude->sProtected()); | |
var_dump($dude->sPrivate()); | |
var_dump($dude->pPublic()); | |
var_dump($dude->pProtected()); | |
var_dump($dude->pPrivate()); | |
//no inherited trait | |
$zombie = new Walker(); | |
var_dump($zombie->zPublic()); | |
var_dump($zombie->zProtected()); | |
//should be exception | |
var_dump($zombie->zPrivate()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment