Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does/Why php forces you to use the object constructor

I have been doing some research on objects in PHP. All the examples I have seen use the object constructor even on their own objects. Does PHP force you to do this and if so why?

For example:

<?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! :-)";
       }
    }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    echo $me->greet(); 
    ?>

But if I do this:

<?php
class Person {
    public $isAlive = true;
    public $firstname;
    public $lastname;
    public $age;
}
$person->firstname = "John";
echo $person->firstname;
?>

I get a http error code 500.(ie: My code crashed).

like image 445
georgiaboy82 Avatar asked May 27 '15 14:05

georgiaboy82


1 Answers

You're incorrectly associating the __construct() function with the way in which you instantiate a class/object.

You don't have to use the __construct() function (it's optional). However, before you can use a class's methods, you do have to create an instance of it first.

<?php
class Person {
    public $isAlive = true;
    public $firstname;
    public $lastname;
    public $age;
}
$person = new Person(); //Add this line
$person->firstname = "John";
echo $person->firstname;
?>
like image 96
rick6 Avatar answered Sep 22 '22 00:09

rick6