Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class works without declaring variables?

Tags:

oop

php

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

like image 997
Max Avatar asked Oct 22 '25 04:10

Max


2 Answers

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.

like image 109
hakre Avatar answered Oct 23 '25 18:10

hakre


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

like image 25
gitaarik Avatar answered Oct 23 '25 19:10

gitaarik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!