4

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

this giving me an error

Catchable fatal error: Object of class Hide could not be converted to string

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

hakre
  • 193,403
  • 52
  • 435
  • 836
user439555
  • 95
  • 6

5 Answers5

7

You're trying to echo a Hide() object, which PHP doesn't 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();

Instead of echo, try

print_r($run->name());
Christopher Armstrong
  • 7,907
  • 2
  • 26
  • 28
  • 3
    It's worth noting that you can hook into the magic function `__toString` which PHP tries to call when you echo an object. – Kevin Jun 04 '11 at 17:02
4

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

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

or add a __toString() method to Hide.

cem
  • 3,311
  • 1
  • 18
  • 23
2

You should be returning

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

or define a tostring for the Hide class

public function __toString() {
     return "str";   }
Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184
0

You are returning an instance of the class Hide

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

and then you try to echo that instance here:

echo $run->name();

echo, expects a string. That's why you get the error.

Fredrik
  • 2,016
  • 3
  • 15
  • 26
0

As Christopher Armstrong said, you're trying to use a Hide() object as a string, and PHP doesn't know how to convert it. You could, however, try to convert it to a string using this code:

$myText = (string)$myVar;

Wich I found here: ToString() equivalent in PHP

I also found something here that may help you.

Community
  • 1
  • 1
RobinJ
  • 5,022
  • 7
  • 32
  • 61