Handling PHP properties like those in C getter amp setter

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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;
    }
}

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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/33632621/handling-php-properties-like-those-in-c-sharp-getter-setter

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils