问答详情
源自:2-4 PHP类和对象之定义类的方法

为啥不用return

speedup 方法里面为啥不用return speed 下面可以直接用echo $car->speed打印出来?????

提问者:joymc 2016-03-17 18:27

个回答

  • dayu_
    2016-03-17 19:25:45

    这个是可以的,你需要根据需要来决定是否使用 return。按照你说的应该是使用 return $this->speed,而不是使用 return speed。你写的有两个错误,首先变量要使用 符号调用。其次在类中的函数中不能直接使用 $speed 调用类实例的局部变量,你如果在函数中直接 return $speed 那么这个 $speed 变量是属于这个函数的局部变量而不是类实例中声明的 $speed 变量,你不赋值直接输出这个 $speed 会显示这是一个未定义的变量。

    正解:

    class Car {

        public $speed = 0;

        public function speedUp() {

            $this->speed += 10;

            return $this->speed;

        }

    }

    $car = new Car();

    echo $car->speedUp();

    错误:return speed、return $speed