1

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()?

  • This is the old style _constructor_ - https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon. See the section titles "Old-style constructors". – waterloomatt Jun 10 '21 at 01:12

2 Answers2

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

This is the old style constructor. See the section titles "Old-style constructors".

https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon

It is essentially the same as calling __construct, but using the old style will result in a deprecation notice in PHP 7.4

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

On a side note, make sure to turn on error reporting when developing. https://stackoverflow.com/a/21429652/296555

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
waterloomatt
  • 3,662
  • 1
  • 19
  • 25
0

I didn't got any error (my bad) but it forced me into the logic of the process:

  • The engine sees the "new" keyword and creates a new object.
  • Since function names are case-insensitive, the method is taken to be the constructor.
  • So, the constructor creates a new instance of "Y" and immediately echoes the string stated in y().

It could be seen as a feature, but also as a valid reason for deprecation.

Just as a comparison, JS in similar case throws no exception:

class Y {
            constructor() {
                this.name = "Red";
            }
            Y() {
                return this.name;
            }
        }
        let x = new Y(); //creates a new instance of Y
        console.log(x.Y()); // outputs "Red"