Skip to content
Advertisement

PHP: Why am I getting “Undefined property: myCar::$model”

I’m new to PHP and I am trying to follow a course.

<?php 
    class myCar {
        function myCar() {
            $this->model = "Sports";
        }
    }

    $Range_Rover = new myCar();

    echo $Range_Rover->model;
?>

According to the tutorial I should get the output “Sports” What is causing the code to result in an error of undefined property?

Warning: Undefined property: myCar::$model in C:xampphtdocsTestindex.php on line 16

Screenshot of tutorial results

Many thanks, Stuart

Advertisement

Answer

Correct way to do it:

<?php 
    class myCar {
        public $model;
        function __construct() {
            $this->model = "Sports";
        }
    }

    $Range_Rover = new myCar();

    echo $Range_Rover->model;

Output: https://3v4l.org/bnNrm

Note: Why above is needed

a) Defining constructor name as class name is an older practice, and it will give you deprecation message for some php version (php 7 versions).

b) Also from php8 it will be treated like a normal function, not as a constructor, so your purpose will not solve.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement