2

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?

3
  • 1
    What is $sign? Also, your forumla variables should have $ in front of them: Variable $var1; Commented Oct 18, 2018 at 7:19
  • You just did, except for a few syntax errors. I don't really know, what's the issue here. Commented Oct 18, 2018 at 7:19
  • $sign is another parameter of Formula class Commented Oct 18, 2018 at 7:23

1 Answer 1

1

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;
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

PHP doesn't support typed attributes of a class yet. But it will as of 7.3. See wiki.php.net/rfc/typed_properties_v2 for details.
@Gordon, yes but it will be in future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.