Skip to content

Instantly share code, notes, and snippets.

@antonmedv
Created October 21, 2013 10:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonmedv/7081560 to your computer and use it in GitHub Desktop.
Save antonmedv/7081560 to your computer and use it in GitHub Desktop.
Example of getters and setters in PHP.
<?php
$foo = new Foo();
$foo->id = 1;
$foo->text = 'Hello';
echo $foo->id; // 1
echo $foo->text; // Hello World!
<?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!';
}
}
@Rabotyahoff
Copy link

Great idea.I would use
protected function setText($text)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment