简体   繁体   中英

Class works without declaring variables?

I'm learned php as functional and procedure language. Right now try to start learn objective-oriented and got an important question.

I have code:

class car {

    function set_car($model) {
        $this->model = $model;
    }

    function check_model()
    {
        if($this->model == "Mercedes") echo "Good car";
    }

}

$mycar = new car;
$mycar->set_car("Mercedes");

echo $mycar->check_model();

Why it does work without declaration of $model?

var $model; in the begin?

Because in php works "auto-declaration" for any variables? I'm stuck

Every object in PHP can get members w/o declaring them:

$mycar = new car;
$mycar->model = "Mercedes";
echo $mycar->check_model(); # Good car

That's PHP's default behaviour. Those are public. See manual .

Yes, if it doesn't exist, PHP declares it on the fly for you.

It is more elegant to define it anyway, and when working with extends it's recommended, because you can get weird situations if your extends are gonna use the same varnames and also don't define it private, protected or public.

More info: http://www.php.net/manual/en/language.oop5.visibility.php

PHP class members can be created at any time. In this way it will be treated as public variable. To declare a private variable you need to declare it.

Yes. But this way variables will be public. And declaration class variable as "var" is deprecated - use public, protected or private.

No, it's because $model is an argument of the function set_car. Arguments are not exactly variables, but placeholders (references) to the variables or values that will be set when calling the function (or class method). Eg, $model takes the value "Mercedes" when calling set_car.

I think this behavior can lead to errors. Lets consider this code with one misprint

declare(strict_types=1);

class A
{
    public float $sum;
    public function calcSum(float $a, float $b): float
    {
        $this->sum = $a;
        $this->sums = $a + $b; //misprinted sums instead of sum
        return $this->sum;
    }
}

echo (new A())->calcSum(1, 1); //prints 1

Even I use PHP 7.4+ type hints and so one, neither compiler, nor IDE with code checkers can't find this typo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM