简体   繁体   中英

Unable to understand __toString() function OOP PHP

I am now learning object oriented php and i face a problem with the magic method named __toString().

There are no calls for that function. Is it similar to other magical function?

If a use it to my class then is it convert all the objects all string or not?

Code-

class MyClass
{
  public $prop1 = "I'm a class property!";

  public function __construct()
  {
      echo 'The class "', __CLASS__, '" was initiated!<br />';
  }

  public function __destruct()
  {
      echo 'The class "', __CLASS__, '" was destroyed.<br />';
  }

  public function __toString()
  {
      echo "Using the toString method: ";
      return $this->getProperty();
  }

  public function setProperty($newval)
  {
      $this->prop1 = $newval;
  }

  public function getProperty()
  {
      return $this->prop1 . "<br />";
  }
}

// Create a new object
$obj = new MyClass;

// Output the object as a string
echo $obj;

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "End of file.<br />";

?>

The output-

The class "MyClass" was initiated! Using the toString method: I'm a class property! The class "MyClass" was destroyed. End of file.

The magic __toString method is called when an object of that class is getting used as a string:

class Something {
    private $whatever;
    public function __construct($whatever) {
        $this->whatever = $whatever;
    }
    public function __toString() {
        return $this->whatever;
    }
}

$obj = new Something("Whatever here!");
echo "Object is $obj"; // Object is Whatever here!

See The Docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM