Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling PHP properties like those in C# (getter & setter)

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:

  • Should I use C#-like property handling in PHP?
  • Get and set (private) property in PHP as in C# without using getter setter magic method overloading

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;
    }
}
like image 293
Can O' Spam Avatar asked Mar 14 '23 05:03

Can O' Spam


1 Answers

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...

like image 175
Flosculus Avatar answered Mar 17 '23 05:03

Flosculus