Does / Why php forces you to use an object constructor

I am researching objects in PHP. All the examples I've seen use the object constructor even on their objects. Does PHP force you to do this, and if so, why?

For instance:

<?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 an http 500 error code. (I.e. my code crashed).

+6
source share
3 answers

You incorrectly bind the __construct() function to how you instantiate the class / object.

You do not need to use the __construct() function (optional). However, before you can use class methods, you first need to instantiate it.

 <?php class Person { public $isAlive = true; public $firstname; public $lastname; public $age; } $person = new Person(); //Add this line $person->firstname = "John"; echo $person->firstname; ?> 
+3
source

Since the definition of a class is exactly that, the definition.

To create an instance of a class (the actual object), you must create it. In fact, you can create many different objects / instances of the same class.

And you do not need to define a constructor method ..... but you need to create an instance using new

+3
source

There are two ways to work with class variables. 1. The variable must be publicly available, such as:

 class Person { public $isAlive = true; public static $firstname; public $lastname; public $age; } Person::$firstname = "John"; echo Person::$firstname; 

2. access to a variable through a class object

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

By the way, PHP can create an object by itself php 5.5. Your code is not crashing. It just gives a warning: Warning: creating a default object from an empty value in ...

So WHY? This is how PHP works with memory. In the first case, static means that php has already allocated memory for the variable, and you can work with it. The second case. Using the NEW command, you give the php command to allocate memory and load the class into it. So, after creating the class, you have access to var.

In the third case, PHP calls the new person himself and gives you a warning. I do not recommend relying on the default php behavior. ALWAYS create an object explicitly

+2
source

Source: https://habr.com/ru/post/988017/


All Articles