Asked 7 years ago
29 Mar 2017
Views 36641
jaydeep

jaydeep posted

how to convert object to string in PHP ?

How to convert object to string in PHP ,



class obj {
	public $id='';
	public $name='';
	public $desc='';
	public $user='';
}
$obj = new obj();
$obj->toString();


is there any pre-defined function toString function which will convert object to string ,
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

use serialize to convert object to string format.


$obj = new obj();
serialize($obj);


you can also string to object with unserialize ,


$j=unserialize($obj);
print_r($j);



$j=unserialize($obj);
print_r($j);




class obj {
	public $id='';
	public $name='';
	public $desc='';
	public $user='';

function __toString(){
   return serialize($this);
}

}

Rasi

Rasi
answered Nov 30 '-1 00:00

json_encode used to convert array to string , convert object to array by casting conversion


class obj {
	public $id='';
	public $name='';
	public $desc='';
	public $user='';

function __toString(){
   return json_encode((array)$this);
}

}
Post Answer