Skip to content


PHP5 – Smarty register_object fatal error, object reference passed via an array.

Earlier, I found an interesting little issue while trying to utilize the register_object function of Smarty while trying to pass an object reference via an array. The classes below can be used to recreate this issue.

class A {
    private $data = array();
    public function __construct() {
        $this->data['object'] = new B();
    }
 
   public functionn getData() {
      return $this->data;
   }
}
 
class B {
    public function myFunction() {
      //dosomething
        return "someData";
    }
}

The following code:

$a = new A();
$data = $a->getData();
foreach($data as $var => $val) {
    if(is_object($val)) {
          $smarty->register_object($var,$val,'null','false');
    } else {
         $smarty->assign($var,$val);
    }
}

Results in:

registered 'object' is not an object (Smarty_Compiler.class.php, 
line 880) in libs/Smarty.class.php on line 1092

This appears to be a smarty compiling bug. To fix the above error, I changed the code to the following.

$a = new A();
$data = $a->getData();
foreach($data as $var => $val) {
    if(is_object($data[$var])) {
          $smarty->register_object($var,$data[$var],'null','false');
    } else {
         $smarty->assign($var,$val);
    }
}

The above code fixes the Smarty compiling error and all works as expected.

The behavior within the foreach loop resulted in hours of research to isolate the issue. Just to make sure It wasn’t a PHP5 bug I decided to do an additional test outside of the Smarty instance. I created the following test script.

class A {
	private $data = array();
 
	public function __construct() {
		$this->data['object'] = new B();
	}
 
	public function getData() {
		return $this->data;
	}
}
class B {
	public function myFunction() {
		echo "Fired <br />";
	}
}
 
$a = new A();
$data = $a->getData();
foreach($data as $k => $v) {
	if(is_object($v)) {
		$v->myFunction();
	}
}
 
foreach($data as $k => $v) {
	if(is_object($data[$k])) {
		$data[$k]->myFunction();
	}
}

As expected, both loops will fire the myFunction method on the B class instance, this is definitely not a bug relating to PHP.

Posted in PHP.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.