Giulio Muscarello
Giulio Muscarello

Reputation: 1342

Make a variable behave like a function

I'm making a PHP script which works with polynomials and monomials (an example of monomial is 42xk^2c^3d). The Monomial class is defined as follows:

class Monomial {
    public $coefficient; // i.e. 42
    public $letters;     // an array of Letter objects
    public $literal;     // i.e. xk^2c^3d
    /* Code */
}

Now, in my applications I use both the array of letters and the literal variable. I don't want to update "by hand" the literal variable whenever I update the monomial (e.g. when adding something to it): instead, I want it to be dynamical, so that accessing it calls a function to "build" it. Any ideas?

Upvotes: 0

Views: 68

Answers (2)

Giulio Muscarello
Giulio Muscarello

Reputation: 1342

Use the __get method. An example:

class Monomial {
    public $coefficient;
    public $letters;
    public $literal;

    function __get($var) {
        if ($var != "literal") {
            return $this->data[$var];
        } else {
            foreach ($this->letters as $letter) {
                $return.=$letter->literal;
            }
            return $return;
        }
}

There would be a similar __get method in the Letter object which would generate the literal string on request.

Upvotes: 0

knittl
knittl

Reputation: 265201

Write a function setLetters (or even updateMonomial) which updates both your variables and use that instead of accessing the variable directly. It's generally a good idea to not expose class members.

Upvotes: 2

Related Questions