Created
October 21, 2013 10:11
-
-
Save antonmedv/7081560 to your computer and use it in GitHub Desktop.
Example of getters and setters in PHP.
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 | |
$foo = new Foo(); | |
$foo->id = 1; | |
$foo->text = 'Hello'; | |
echo $foo->id; // 1 | |
echo $foo->text; // Hello World! |
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 | |
/** | |
* @property int $id | |
* @property string $text | |
*/ | |
class Foo | |
{ | |
protected $id; | |
protected $text; | |
public function __get($name) | |
{ | |
$methodName = 'get' . ucfirst($name); | |
return method_exists($this, $methodName) ? $this->{$methodName}() : $this->{$name}; | |
} | |
public function __set($name, $value) | |
{ | |
$methodName = 'set' . ucfirst($name); | |
return method_exists($this, $methodName) ? $this->{$methodName}($value) : $this->{$name} = $value; | |
} | |
public function __isset($name) | |
{ | |
return property_exists($this, $name); | |
} | |
public function setText($text) | |
{ | |
$this->text = $text . ' World!'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great idea.I would use
protected function setText($text)