Max
Max

Reputation: 1349

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

Upvotes: 4

Views: 1465

Answers (6)

Sergei Beloglazov
Sergei Beloglazov

Reputation: 362

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.

Upvotes: 0

sarwar026
sarwar026

Reputation: 3821

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.

Upvotes: 3

gitaarik
gitaarik

Reputation: 46270

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

Upvotes: 3

user1303559
user1303559

Reputation: 436

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

Upvotes: 1

hakre
hakre

Reputation: 197624

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.

Upvotes: 6

Mihnea Simian
Mihnea Simian

Reputation: 1103

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). E.g., $model takes the value "Mercedes" when calling set_car.

Upvotes: 0

Related Questions