Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

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

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 mysterious.

I have two classes:

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

and

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

called by

include_once 'classes/Hello.php';
include_once 'classes/world.php';

$hi= new Hello;    
$wd= new World;`

Result Hello World

I originally accidentally had hello for the name of the class World's method. Result Hello i.e. no World.

Question 1

Why are the methods firing? I have instantiated two objects but have not requested that the method “fire”. I thought I would have to do something like:

$hi->hello();

to get an output.

Question 2

I am even more mystified that I only get Hello if both functions are called hello.

Surely

$hi= new Hello;
$wd= new World;

instantiates two completely separate objects. So how does the actual NAME of a method affect anything?

I have a long way to go but this really confused me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...