John Davidson

php 7.4 - PHP 7.4. Instantiation of a class which contains a method of the same name invokes the method

0 comments
Message:


Is it a kind of a bug or something? When creating an object from a class containing a method with the same name as the class, the statement prints the method's output.(PHP 7.4)


<?php
class Y {
public $name = "Red";
public function y() {
echo $this->name;
}
}
$x = new Y(); // outputs "Red"

Function names are not case-sensitive, and hence this statement outputs y()?



My Answer:
This behavior is not a bug, but rather a feature of PHP called "constructor promotion". In PHP 7.4, a new feature was introduced where you can define a constructor directly in the class definition using the same name as the class itself. When you instantiate an object from this class, the constructor method will be automatically called.

Here is an example to illustrate this feature:

php
class MyClass {
public function MyClass() {
echo "Constructor method called";
}
}

$obj = new MyClass();


When you run this code in PHP 7.4, it will output "Constructor method called", indicating that the constructor method was invoked when the object was created.

So, in conclusion, this behavior is intentional and not a bug in PHP 7.4.

Rate this post

5 of 5 based on 6130 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us