PHP - Add method to a stdClass object

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts: 48

PHP - Add method to a stdClass object

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 ..

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/ 

Similar Topics