Vitalik Jimbei Vitalik Jimbei - 1 month ago 4
PHP Question

cannot define constant in class php

i am learning php now using code academy website but some is not explained properly.

these are the conditions:


  1. Create a class called Cat.

  2. Add two public properties to this class: $isAlive ought to store the value true and $numLegs should contain the value 4.

  3. Add a public $name property, which gets its value via the __construct()or.

  4. Add a public method called meow(), which returns "Meow meow".

  5. Create an instance of the Cat class, which has the $name "CodeCat".

  6. Call the meow() method on this Cat and echo the result.



This is the code created :

<!DOCTYPE html>
<html>
<head>
<title> Challenge Time! </title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<p>
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;

public function __construct() {
$cat->name = $name;;
}
public function meow(){
return "Meow meow";
}
}


$cat = new Cat(true ,4 , CodeCat);
echo $cat->meow();
?>
</p>
</body>
</html>

Answer

In your code you have a constructor with no parameters, so $name will be undefined. And when you want to create a new object Cat you call it with 3 params, but you don't have a constructor like that.

What you want is to have a constructor with 1 param $name and call it with that param like this:

<?php
      // Your code here
      class Cat {
         public $isAlive = true;
         public $numLegs = 4;
         public $name ;

         public function __construct($name) {
              $this->name = $name;
         }
         public function meow(){
              return $this->name;
         }
      }


      $cat = new Cat('CodeCat');  //Like this you will set the name of the cat to CodeCat
      echo $cat->meow();  //This will echo CodeCat
?>
Comments