php - How __toString works in this example?

So I found this problem:
// name1.php
namespace Examples\Names;
class Name {
public function __toString() {
return "Laurel";
}
public static function get() {
return "Eminent";
}
}
// name2.php
namespace Examples;
include "name1.php";
class Name {
public function __toString() {
return "James";
}
public static function get() {
return "Cook";
}
}
echo new Name() . " | " . Names\Name::get();
And I would like to understand why this echoecho new Name() . " | " . Names\Name::get();
take displaysJames | Eminent
.
I think that I got it about second second partNames\Name::get()
that it takes from Examples\Names\NameEminent
because it has that get, but what about first part? Why it takesJames
by default?
Also, when I try to remove switch fromNames\Name::get()
toNames\Name()
just to see if it display __toString from second class -Cook
it doesn't work and I get this errorFatal error: Uncaught Error: Call to undefined function Examples\Names\Name() in C
Can you help me with that? I really want to understand. Thank you!
Answer
Solution:
what about first part
...it uses the class from theExamples
namespace because it's in the same namespace as theecho
statement. And it echoesJames
because of the__toString
- that serves as the default function called behind the scenes by PHP whenever you try to put an object into a string.
switch from Names\Name::get() to Names\Name()
... it would need to benew Names\Name()
I think, if you want to instantiate the class.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.