Define a Student class:
1 class Student { 2 public $name 3 public $age 4 function __construct ( $name , $age ) { 5 $this -&G T;name = $name ; 6 $this ->age = $age 7} 8}
At this point, the new object is directly echo: 1 $person 1 = new Student (' Jack '); 2 echo $person 1;
The result did not print out the object as we expected, but instead reported a fatal error:
An object that is instantiated by the student class cannot be converted to a string, and here is a message: echo must be followed by a string.
Otherwise it will automatically be converted to a string, then how to say an object to a string?
Introduce a Magic method: __tostring (), which is used to respond to a class when it is treated as a string. e.g. echo $obj;
What should be shown. This method must return a string, or a E_RECOVERABLE_ERROR
level of fatal error will be emitted.
Add this magic method to the student class:
1 classStudent {2 Public $name;3 Public $age;4 function__construct ($name,$age) {5 $this->name =$name;6 $this->age =$age;7 }8 function__tostring () {9 returnJson_encode ($this, Json_force_object);Ten } One}
The Json_encode (value, Options) method converts an object to a JSON string, which accepts two parameters.
First parameter: value
The value to encode, in addition to the resource type, can be any data type
This function can only accept UTF-8 encoded data.
Second parameter: Options
A binary mask consisting of the following constants: Json_hex_quot, Json_hex_tag, Json_hex_amp, Json_hex_apos, Json_numeric_check, Json_pretty_print, JSON_ Unescaped_slashes, Json_force_object, Json_unescaped_unicode.
Return value: The success of the encoding returns a string in JSON form or FALSE on failure.
Note: There is a Json_decode method relative to the Json_encode method, which converts a JSON-formatted string into a PHP variable that accepts two parameters
First parameter: JSON string
The second parameter: True/false, True indicates that the string is converted to an object when false, or false when it is a quasi-transposition array.
Return value: Object or Array (when the second argument is true)
At this point in the browser open you can see the conversion success:
Object into a JSON string