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

Objects in PHP Forum

View Course » View Exercise

488 points
53f8a98b7c82caae510043f6_674058757
Submitted by
Thermidor
over 2 years ago

I has the dumb.

I hate when i write code that works but i don't know what i'm doing. Therefore i don't learn anything new. The code academy explanation is not sufficient. So can someone explain to me line by line how this code works. Because i have no clue, apart from assigned variables. I would like to know especially what that arrow -> thing does.

<?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;
            }

            public function greet() {
                return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
            }

        }

        $teacher = new Person("boring", "Scarlet", 12345);
        $student = new Person("Gintoki", "Sakata", 21);

        echo $teacher -> greet();
        echo $student -> greet();
        ?>

0 votes

permalink

I am pretty new myself but I think I know how to answer this question.

In an array you may have several items like:

$colors = array("red", "blue", "yellow");

You can then call one item in the array like this:

echo $colors[1];

That will obviously print "blue".

With an object, you may have several items as well. In this example you have $isAlive, $firstname, $lastname, and $age. So $student is an object of the class Person with the 4 public variables I just mentioned. If you want to return one item, if it was like an array you would say:

echo $student[$age];

but instead it looks like this:

echo $student ->age;

Can someone confirm that explanation is right?

91 points
6ff821e6f7966a8135acd66cc8830acd?s=140&d=retro
Submitted by
jmbunnell
over 2 years ago

2 Comments

D211dc03d1527c910acffa6fb5f73db8?s=140&d=retro Mie Rex about 2 years ago

I have no clue of this whole chapter as well
I would be grateful if someone could give a better explanation than the tutorial
I agree with Thermidor, I hate just copying the code and change the variables around without knowing what the code does.

Picture Lui Kohl about 2 years ago

I think that is correct above, but I agree with the others this whole chapter has done an awful job of explaining objects and classes. I have learned about objects and object constructors in JS and it was explained much better elsewhere. It's really not that complicated when explained clearly.