Created
July 7, 2012 13:49
-
-
Save jk/3066536 to your computer and use it in GitHub Desktop.
Example of PHP traits to implement real properties in PHP classes
This file contains hidden or 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 | |
/** | |
* Real properties PHP trait | |
* Requirements: PHP 5.4 or later | |
*/ | |
trait Properties | |
{ | |
protected $properties; | |
public function __get($name) | |
{ | |
if (method_exists($this, ($method = 'get_'.$name))) | |
{ | |
return $this->$method(); | |
} | |
else return; | |
} | |
public function __isset($name) | |
{ | |
if (method_exists($this, ($method = 'isset_'.$name))) | |
{ | |
return $this->$method(); | |
} | |
else return; | |
} | |
public function __set($name, $value) | |
{ | |
if (method_exists($this, ($method = 'set_'.$name))) | |
{ | |
$this->$method($value); | |
} | |
} | |
public function __unset($name) | |
{ | |
if (method_exists($this, ($method = 'unset_'.$name))) | |
{ | |
$this->$method(); | |
} | |
} | |
} | |
?> |
This file contains hidden or 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 | |
// Require PHP 5.4 or later | |
require 'trait.properties.php'; | |
class Person { | |
use Properties; | |
public function __construct($first, $last) { | |
$this->properties['firstname'] = $first; | |
$this->properties['lastname'] = $last; | |
} | |
public function get_fullname() { | |
echo "Get fullname\n"; | |
return $this->firstname.' '.$this->lastname; | |
} | |
public function get_firstname() { | |
echo "Get firstname\n"; | |
return 'F:'.$this->properties['firstname']; | |
} | |
public function set_firstname($value) { | |
echo "Set firstname=$value\n"; | |
$this->properties['firstname'] = trim($value); | |
} | |
public function get_lastname() { | |
echo "Get lastname\n"; | |
return 'L:'.$this->properties['lastname']; | |
} | |
public function set_lastname($value) { | |
echo "Set lastname=$value\n"; | |
$this->properties['lastname'] = trim($value); | |
} | |
} | |
$person = new Person('John', 'Doe'); | |
echo $person->fullname."\n"; | |
$person->firstname = 'Jens'; | |
$person->lastname = 'Kohl'; | |
echo $person->fullname."\n"; | |
// Output: | |
// | |
// Get fullname | |
// Get firstname | |
// Get lastname | |
// F:John L:Doe | |
// Set firstname=Jens | |
// Set lastname=Kohl | |
// Get fullname | |
// Get firstname | |
// Get lastname | |
// F:Jens L:Kohl | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment