How to pass class-defined variables to class methods in PHP?
P粉436688931
P粉436688931 2023-09-13 21:12:48
0
1
572

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粉436688931
P粉436688931

reply all(1)
P粉594941301

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();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template