dsh125986083 2015-11-01 09:55
浏览 46

PHP在课堂上添加两个数字

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条回答 默认 最新

  • duanduan8439 2015-11-01 10:01
    关注
      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

    评论

报告相同问题?

悬赏问题

  • ¥20 python忆阻器数字识别
  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真