PHP在类中添加两个数字


PHP add two numbers in class

我试图在PHP类中构建一个函数,但无论何时调用该函数,我都只返回第一个变量。

        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;
    }
}

我是不是做错了什么,因为我真的看不出这个逻辑有什么错。

它对我很有效。以下是我尝试的结果,它输出了15

PHP代码:

<?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;
?>

输出:

15
  class Nums  
  {
    private $a = 7;
    private $b = 8;
    public function sum() 
    {
        return $this->a + $this->b;
    }
  }
$numObj = new Nums();
echo $numObj->sum();

运行此代码会为我返回15