1

I'm trying to build a function inside a PHP class, however whenever I invoke the function, I am only returning the first variable.

        class Nums  
{
    private $a = 7;
    private $b = 8;

    public function sum() 
    {
        return $this->a + $this->b;
    }

    public function __set($name,$value) {
      switch($name) { 
        case 'a': 
          return $this->setA($value);
        case 'b': 
          return $this->setB($value);
      }
    }

    public function __get($name) {
      switch($name) {
        case 'a': 
          return $this->getA();
        case 'b': 
          return $this->getB();
      }
    }

    private function setA($i) {
      $this->a = $i;
    }

    private function getA() {
      return $this->$a;
    }

    private function setB($i) {
      $this->b = $i;
    }

    private function getB() {
      return $this->$b;
    }

}

Am I doing something wrong here, because I can't really see what is wrong with this logic.

3
  • This looks fine to me. How are you using this class? Commented Nov 1, 2015 at 10:06
  • I added the set and get components which I used to modify the class, I didn't think this was the issue. Obviously it was. When I called the sum fuction I was trying to get the private variable, when I should be using the name I defined in the swtich statement. Commented Nov 1, 2015 at 10:26
  • yes, sometimes the problem shows up at unexpected places :) Commented Nov 1, 2015 at 10:46

2 Answers 2

1

It's working for me. Here's what i tried and it output 15.

PHP CODE :

<?php

class Nums  
{
    private $a = 7;
    private $b = 8;

    public function sum() 
    {
        return $this->a + $this->b;
    }

}

$obj = new Nums();
$c = $obj->sum();
echo $c;

?>

OUTPUT :

15
Sign up to request clarification or add additional context in comments.

Comments

0
  class Nums  
  {
    private $a = 7;
    private $b = 8;

    public function sum() 
    {
        return $this->a + $this->b;
    }
  }

$numObj = new Nums();
echo $numObj->sum();

Running this code returns 15 for me

Comments

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.