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

Objects in PHP Forum

View Course » View Exercise

91 points
1594bc0f3ae0028583cf34ce7bff109a?s=140&d=retro
Submitted by
Fabio Mikhail
over 1 year ago

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

So, I have this code

       <?php
        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

permalink

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
9a74e1277d8e32358137a88e715f067c?s=140&d=retro
Submitted by
Bret Wagner
over 1 year ago

1 Comment

1594bc0f3ae0028583cf34ce7bff109a?s=140&d=retro Fabio Mikhail over 1 year ago

Clear. Thank you!