Page 1 of 1

PHP - Add method to a stdClass object

Posted: 02 May 2015, 06:51
by PloMar
How can I add a method to a stdClass object?
For example I try this code:

Code: Select all

$ob = new stdClass;
$ob->prop = 'val';
$ob->site = function($dom) {
  return 'http://'. $dom .'/';
};
echo $ob->site('coursesweb.net'); 
- but it generates this error:

Code: Select all

 Call to undefined method stdClass::site() in ..

PHP - Add method to a stdClass object

Posted: 02 May 2015, 06:55
by Admin
You cannot dynamically add a method to the stdClass and execute it in the normal way.
But you can assign that object method to a variable, then access that variable like a function.
Example:

Code: Select all

$ob = new stdClass;
$ob->prop = 'val';
$ob->site = function($dom) {
  return 'http://'. $dom .'/';
};

$site = $ob->site;  // assign the method to a variable
echo $site('coursesweb.net');  // https://coursesweb.net/