我想将我在类中定义的变量的值传递给它的方法。我知道我可以在方法的括号中使用=符号设置默认值,但这似乎是多余的,因为我已经定义了变量。这可行吗?
class Car {
var $num_wheels = 4;
var $model = "BMW";
function MoveWheels($num_wheels, $model) {
echo "The $num_wheels wheels on the $model are spinning.";
}
}
$bmw = new Car();
$bmw -> MoveWheels(); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我找到了对我的问题的答案!你可以使用
$this->将类定义的变量传递给一个方法。这样做完全消除了将变量放在方法的括号内的需求。class Car { var $num_wheels = 4; var $model = "BMW"; function MoveWheels() { echo "这辆 $this->model 的 $this->num_wheels 个车轮正在旋转。"; } } $bmw = new Car(); $bmw -> MoveWheels();