Skip to content

Instantly share code, notes, and snippets.

@jk
Created July 7, 2012 13:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jk/3066536 to your computer and use it in GitHub Desktop.
Save jk/3066536 to your computer and use it in GitHub Desktop.
Example of PHP traits to implement real properties in PHP classes
<?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();
}
}
}
?>
<?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