Objects in PHP
Property Panic (1)

Great work, now we can add some properties to our class.

As you remember, properties are pieces of data bound to an object, and you can imagine an object as a bundle of information and actions.

class Fruit {
  public $count = 3;
  public $type;

$apple = new Fruit();
$apple->type = "apple";
print $apple->count; // 3
print $apple->type;  // apple
  1. In the example above, we first create a new class called Fruit.
  2. Then we add a property, $count, and set its value to 3.
  3. Next, we add a property, $type, but don't store anything in it yet.
  4. After the class definition, we create new instance of Fruit and store it in $apple.
  5. Then we set the $type property of $apple to the string "apple".
  6. Finally, we print out the two properties of $apple.

Let's try this out!

  1. Add a public $isAlive property to the Person class and assign the value true to $isAlive, like the $count property above.
  2. Add three further public properties to thePerson class: $firstname, $lastname and $age. Don't assign any values to these like the $type property above.
  3. echo the value of the $teacher's $isAlive property.
Stuck? Get a hint! Hint
Get live, fast support from Codecademy Advisors when you get stuck. Learn more.

Your code should look similar to the following:

class Classname {
  public $prop1 = true;
  public $prop2;
  public $prop3;
  public $prop4;
  $obj1 = new Classname();
  $obj2 = new Classname();
  echo $obj1->prop1;

Note: There is no $ before the prop1 after the ->.

View Preview