Why is a method with the same name as the class being called automatically?

前端 未结 1 1323
无人及你
无人及你 2020-12-11 07:08

EDIT: Title edited to make it more useful. Originally I had no idea that it was the use of a shared word that was causing the problem.

This is very basic but rather

相关标签:
1条回答
  • 2020-12-11 07:23

    Both methods get called, when you create a new instance of this class, because the methods have the same name as the class itself and so they are the constructor of this class:

    class Hello
    {
            public function hello()
        {
            echo "Hello";
        }
    }
    class World
    {
        public function world()
        {
            echo " World";
        }
    }

    So when you took an instance from both classes, both constructors got called.


    Now when you renamed both methods to hello only 1 method was counted as constructor and the other one was a normal method in the other class. That's why you only saw Hello as output.


    But don't use the name of the class as constructor! It will be deprecated in PHP 7. Use __construct().

    0 讨论(0)
提交回复
热议问题