Home > Mobile >  How do you pass class-defined variables into a method of the class using PHP?
How do you pass class-defined variables into a method of the class using PHP?

Time:07-31

I'd like to pass the value of the variables I've defined in a class to its method. I know that I can set a default value within the brackets of my method using an = sign, but it seems redundant since I've already defined the variables. 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();

CodePudding user response:

I found an answer to my question! You can pass class-defined variables into a method using $this->. Doing so eliminates placing variables within your method's brackets entirely.

class Car {

    var $num_wheels = 4;
    var $model = "BMW";

    function MoveWheels() {
        echo "The $this->num_wheels wheels on the $this->model are spinning.";
    }
}

$bmw = new Car();
$bmw -> MoveWheels();

CodePudding user response:

Initial question was I'd like to pass the value of the variables I've defined in a class to its method. This doesn't involve necessary changing the method definition.

$bmw=new Car();
$bmw->MoveWheels($bmw->num_wheels,$bmw->model);
//maybe if needed, change param visibility 
//public $num_wheels
  • Related