Handling PHP properties like C # (getter & setter)

I did some research over time and wanted to know whether it is possible to use properties in a PHP class, like C #, I found these questions in the game which had good answers and pointers, but didn’t really help me: / p>

Although, as I said, they give good answers, I still can’t decide, for example, I want to be able to do something like:

class Foo 
{
    public $bar
    {
        get { return $this->bar; }
        set { $this->bar = value; }
    }
}

But I can not!

What is the best way to do this within the limits of PHP?

What I could 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;
    }
}
+4
2

, PHP. . , :

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

... .

, Cat, . -, "" , , , , , , ...

+3

, , . , .

private String _name;

public String Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}

​​ , :

private $_name;

public function getName()
{
    return $_name;
}

public function setName($name)
{
    $_name = $name;
}

:

C#  : Object.Name = "This is my Name";
PHP : Object->setName ("This is my Name");

# (, , ), , Flosculus - . , , . :

__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.

furColor , .

, $cat->furColor = 'black.

  • furColor , __set .
  • GetterSetterExample setFurColor , .
  • , , Cat .
  • setFurColor .

, . " " #. , , ? -, . PHP , , . - , , , . , , . Flosculus , () .

+3

Source: https://habr.com/ru/post/1615260/


All Articles