PHP在课堂上添加两个数字

时间:2015-11-01 09:55:29

标签: php class variables add

我正在尝试在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;
    }

}

我在这里做错了,因为我无法真正看出这种逻辑有什么问题。

2 个答案:

答案 0 :(得分:0)

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

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

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

运行此代码为我返回15

答案 1 :(得分:0)

这对我有用。这是我尝试过的,它输出<?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; ?>

PHP代码:

15

输出:

{'A': [DatetimeIndex([], dtype='datetime64[ns]', name=u'Timestamp', freq=None)],
 'B': [DatetimeIndex(['2010-04-15 16:19:00', '2010-04-15 16:20:00',
                 '2010-04-15 16:23:00'],
            dtype='datetime64[ns]', name=u'Timestamp', length=6, freq=None)]}