Asked 7 years ago
22 Mar 2017
Views 8494
lain

lain posted

Object of class could not be converted to string in PHP

i made PHP Class , doing some experiment with class concept . creating dynamic array which give field name and try to access property with other function in PHP , and getting Catchable fatal error

class obj {
	public $id='';
	public $name='';
	public $desc='';
	public $user='';
	public $dynamic = array("id","name","desc","user");
	
	public function process(){
		foreach($this->dynamic as $value){
		echo $this->$value;
		}
	}
}
$ob = new obj();
$ob->user=new user();
$ob->process();



getting Catchable fatal error ::

Object of class could not be converted to string in PHP
Rasi

Rasi
answered Nov 30 '-1 00:00


check property before use it,
check wheather object property is string of itself object


foreach($this->dynamic as $value){
             if(is_object($this->$value))
                 echo $this->$value;
}


is_object used to check it . if it object avoid it. thats the solution
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

if you avoid $ob->user=new user(); line and if you assign $ob->user="username"; than error get solved

Error because one try to access Class , instead of String .
property set dynamically so no control over it . so is there any other solution so i can omit Object of class could not be converted to string in PHP - lain  
Mar 23 '17 05:47
Post Answer