I want to pass the value of a variable I defined in a class to its method. I know I can set a default value using the =
notation within the parentheses of the method, but this seems redundant since I already have the variable defined. Is this possible?
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();
P粉5949413012023-09-14 00:20:11
I found the answer to my question! You can pass class-defined variables to a method using $this->
. Doing so completely eliminates the need to put variables within parentheses of the method.
class Car { var $num_wheels = 4; var $model = "BMW"; function MoveWheels() { echo "这辆 $this->model 的 $this->num_wheels 个车轮正在旋转。"; } } $bmw = new Car(); $bmw -> MoveWheels();