What does this error show? Hide object cannot be converted to string

I have this code

class Hide { private $myname; function getmyname() { $myname = __class__; return $myname; } } class damu { private static $name; public function name() { var_dump($this->name); if( $this->name == null ){ $this->name = new Hide(); } return $this->name; } } $run = new damu(); echo $run->name(); 

it gives me an error

Fatal error allowed: Hide object cannot be converted to a string

what is the meaning of this and how to resolve it.

+4
source share
5 answers

You have to come back

 return $this->name->getmyname(); 

or define a string for the Hide class

 public function __toString() { return "str"; } 
+2
source

You are trying to repeat a Hide () object that PHP does not know how to convert to a string. This is due to the following lines:

  if( $this->name == null ){ $this->name = new Hide(); } return $this->name; 

and then

 echo $run->name(); 

Try echo instead

 print_r($run->name()); 
+7
source

You return a Hide instance and try to echo it. Since your implementation does not have a __toString() method, there is no string representation, and you will get this error. Try the following:

 $run = new damu(); echo $run->name()->getmyname(); 

or add the __toString() method to Hide .

+4
source

You are returning an instance of the Hide class

 if( $this->name == null ){ $this->name = new Hide(); } return $this->name; 

and then you try to repeat this instance here:

 echo $run->name(); 

echo , expect a string. That is why you get an error.

0
source

As Christopher Armstrong said, you are trying to use the Hide () object as a string, and PHP does not know how to convert it. However, you can try converting it to a string using this code:

 $myText = (string)$myVar; 

I found here: equivalent of ToString () in PHP

I also found something here that can help you.

0
source

All Articles