PHP Object Oriented Programming Analysis of Usage of __tostring of and __invoke of

  • 2021-12-12 03:55:24
  • OfStack

This article illustrates the use of PHP object-oriented programming __tostring () and __invoke (). Share it for your reference, as follows:

__tostring() Magic method

This method is automatically called when an object is used as a string, and in this method, a string of 1 can be returned to indicate the result after the object is converted to a string. This magic method is commonly used.

Note: If this method is not defined, the object cannot be used as a string!

Class is not defined in the __tostring() Method:


<?php
ini_set('display_errors', 1);
class A{
  public $name;
  public $age;
  public $sex;
  function __construct($name, $age, $sex){
    $this->name = $name;
    $this->age = $age;
    $this->sex = $sex;
  }
}
$obj1 = new A(' Zhang 3', 15, ' Male ');
echo $obj1;  //echo  An error will be reported if the object is not a string and is followed by a string 
$v1 = "abc" . $obj1; //. Is a string connector, an error will be reported 
$v2 = "abx" + $obj1; //+ Is an addition operator, and an error is reported 
?>

The three error reports are

Catchable fatal error: Object of class A could not be converted to string
Catchable fatal error: Object of class A could not be converted to string
Notice: Object of class A could not be converted to int

Class is defined in the __tostring() Method


<?php
ini_set('display_errors', 1);
class A{
  public $name;
  public $age;
  public $sex;
  function __construct($name, $age, $sex){
    $this->name = $name;
    $this->age = $age;
    $this->sex = $sex;
  }
  function __tostring(){
    $str = " Name: " . $this->name;
    $str .= " Age: " . $this->age;
    $str .= " , gender: " . $this->sex;
    return $str;  // You can return "any string content" here 
  }
}
$obj1 = new A(' Zhang 3', 15, ' Male ');
echo $obj1;  // Call __tostring(), Can't report an error 
?>

Running result

Name: Zhang 3 Age: 15, Sex: Male

__invoke() Magic method

This method is automatically called when the object is used as a function. This is not usually recommended.


class A{
  function __invoke(){
    echo "<br /> I am 1 An object, don't treat me like 1 A function to call! ";
  }
}
$obj = new A();
$obj();  // The method in the class is called: __invoke()

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: