Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

immutability - PHP: immutable public member fields

I need to create an immutable class which is simply a member field container. I want its fields to be instantiated once in its constructor (the values should be given as parameters to the constructor). I want the fields to be public but immutable. I could have done it with Java using the final keyword before each field. How is it done in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use __set and __get magic methods and declare that property as protected or private:

/**
 * @property-read string $value
 */
class Example
{
    private $value;

    public function __construct()
    {
        $this->value = "test";
    }

    public function __get($key)
    {
        if (property_exists($this, $key)) {
            return $this->{$key};
        } else {
            return null; // or throw an exception
        }
    }

    public function __set($key, $value)
    {
        return; // or throw an exception
    }
}

Example:

$example = new Example();
var_dump($example->value);
$example->value = "invalid";
var_dump($example->value);

Outputs:

string(4) "test"
string(4) "test"

@property-read should help your IDE acknowledge existence of this magic property.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...