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

Objects in PHP Forum

View Course » View Exercise

865 points
Picture
Submitted by
ggLondon
about 3 years ago

Some clarification please

I'm just trying to get using objects clear in my mind.

    <?php
      class Cat{
         public $isAlive = true;
         public $numLegs = 4;  

          public function __construct($name){
            $this->name = $name;  
          }               
          public function meow(){
            return "Meow Meow";
          }
      }         
      $cat1 = new Cat("CodeCat");
      echo $cat1->meow();
    ?>

Is it right to say that the public properties that I have created $isAlive + $numLegs now have fixed values and so in order to create a public property of the Cat class that can have different values ($name) I need to create that property using the __construct method. And so when I create a new instance of the Cat class ($cat1) I am able to affect the value of the $name property.

Some feedback would be much appreciated. Thanks


3 votes

permalink

Yes, see it as a blueprint for a car. You want to be able to create lots of cars! Every car is unique, but still a car, but not the same car. Example time!

class Car {

public $color;
public $wheels;
public $doors;

public function __construct($car_color, $wheel_amount, $door_amount){
$this->color = $car_color;
$his->wheels = $wheel_amount;
$this->doors = $door_amount;
}
}

$my_car = new Car("Red", "4", " 4");
$your_car = new Car("Blue", "4", "2");

Hope it helps!

450 points
5240e713abf821aa28001257_703076796
Submitted by
Robinvb
about 3 years ago

1 Comment

Picture ggLondon about 3 years ago

Thanks Robin I will copy and paste this for future reference. Cheers.x