Szymon Kuźnik
Szymon Kuźnik

Reputation: 21

PHP class object as other class parameter

I have a problem, I need to rewrite my c++ program in PHP, I have very little experience.

Here is my code:

class Variable {
    public $power;
    public $shortcut;
    public $value;
    public function __construct($a, $b, $c) {
        $this->shortcut=$a;
        $this->value=$b;
        $this->power=$c;
    }
};

class Formula {
    Variable var1;
    Variable var2;
    Variable var3;
    $sign;
};

Formula class have 3 parameters which are objects of Variable class, How do I write something like that in PHP?

Upvotes: 2

Views: 47

Answers (1)

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

PHP doesn't support typed attributes of a class. You can create accessor methods and mutator methods to control of attributes type. For example:

class Formula {

    /**
     * @var Variable
     */
    private $var1;

    /**
     * @var Variable
     */
    private $var2;

    /**
     * @var Variable
     */
    private $var3;

    public function setVar1(Variable $value)
    {
        $this->var1 = $value;
    }

    public function getVar1()
    {
        return $this->var1;
    }

    public function setVar2(Variable $value)
    {
        $this->var2 = $value;
    }

    public function getVar2()
    {
        return $this->var2;
    }

    public function setVar3(Variable $value)
    {
        $this->var3 = $value;
    }

    public function getVar3()
    {
        return $this->var3;
    }
};

Upvotes: 1

Related Questions