This forum is now read-only. Please use our new forums at

Objects in PHP Forum

View Course » View Exercise

91 points
Submitted by
Fabio Mikhail
over 2 years ago

Why do I have to declare the same properties two times?

So, I have this code

        class Person {
            public $isAlive = true;
            public $firstname;
            public $lastname;
            public $age;

            public function __construct($firstname, $lastname, $age) {
                $this->firstname = $firstname;
                $this->lastname = $lastname;
                $this->age = $age;

        $teacher = new Person("boring", "12345", 12345);
        $student = new Person("fabio", "mikhail", 19);

        echo $student->age;

What I don't understand is why should I declare firstname, lastname and age two times, one time outside the _construct and the other one inside the _constructor.

0 votes


outside the construct you are declaring that the code should have the variables.

inside the construct you are actually setting the values.

if the variables aren't declared prior to the construct you'll get an undeclared variable.

426 points
Submitted by
Bret Wagner
over 2 years ago

1 Comment

1594bc0f3ae0028583cf34ce7bff109a?s=140&d=retro Fabio Mikhail over 2 years ago

Clear. Thank you!