Mike Mike - 11 months ago 56
PHP Question

PHP - newbie to the language

Hi i'm just learning php and am trying various code samples/exercises. Below is one

// class definition
class Bear
// define properties

public $name;
public $weight;
public $age;
public $colour;
public $sex;

// constructor
public function _construct()
$this->age = 0;
$this->weight = 100;
$this->colour = "Brown";

// create instance

$baby = new Bear;
$baby->name = "Baby bear";
$sex->sex = "Male";

echo $baby->name." is ".$baby->colour." and weighs ".$baby->weight." units at birth and his sex is ".$baby->sex;

When I run this file it returns

Baby bear is and weighs units at birth and his sex is

It does not pick up the variables.
Any advice would be great.

Answer Source

The program is quite simple and its not at all complex. The issue here is

1) The way of constructing a constructor, You created a class Bear. Make the constructor as in your code

public Bear() { //Your code here } //Deprecated in PHP7
public function __construct() 

2) You created a instance named $baby and $sex is a variable for that object. But you have written

$sex->sex = "Male"; //This is wrong as $sex is a variable not an object
$baby->sex = "Male"; //Correct way of representation

Make these changes in your code and it will work for sure.

Hope this helps you.