I have been doing some research over time and wanted to know if using properties in a PHP class can be done like C#, I have found these questions which game some good answers and pointers, but didn't help me really:
Although, as I said, these give good answers, I still can't make up my mind on these, for example, I want to be able to do something such as:
class Foo
{
public $bar
{
get { return $this->bar; }
set { $this->bar = value; }
}
}
But I am unable to!
What is the best way to do this within the constraints of PHP?
The kind of thing I have been able to come up with is this:
class user
{
private static $link;
private static $init;
private function __construct ()
{
global $link;
static::$link = $link;
}
public static function __INIT__ ()
{
return static::$init = (null === static::$init ? new self() : static::$init);
}
public static $username;
public function username( $value = '' )
{
if ( $value == '' || empty ( $value ) || !$value )
return static::$username;
else
static::$username = $value;
}
}
This is what PHP magic methods are for. They allow you to dynamically set properties through a mediator method. Here, let me show you an example:
abstract class GetterSetterExample
{
public function __get($name)
{
$method = sprintf('get%s', ucfirst($name));
if (!method_exists($this, $method)) {
throw new Exception();
}
return $this->$method();
}
public function __set($name, $v)
{
$method = sprintf('set%s', ucfirst($name));
if (!method_exists($this, $method)) {
throw new Exception();
}
$this->$method($v);
}
}
class Cat extends GetterSetterExample
{
protected $furColor;
protected function getFurColor()
{
return $this->furColor;
}
protected function setFurColor($v)
{
$this->furColor = $v;
}
}
$cat = new Cat();
$cat->furColor = 'black';
Yeah... it terrifies me as well.
This is why most people are content with using methods like the ones in Cat
, but public. Apparently there is discussion on adding "real" getters and setters, but there appears to be a lot of conflict between those who hate them for concerns of readability, semantics and principle...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With