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).
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;
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With