I want to add a function on an object that returns a specific value from that object.
I have the following code now:
<?php
namespace sdk;
use core\Sdk;
class Contents extends Sdk {
public $url;
public $id;
public function __call($method, $args) {
if (isset($this->$method)) {
$func = $this->$method;
return call_user_func_array($func, $args);
}
}
public function getContents($id = '') {
$request = 'contents/list/'.$id;
return $this->getRequest($request);
}//getContents
public function getContent($id) {
$request = 'contents/detail/'.$id;
$this->object = $this->getRequest($request);
$this->object->getItemAttribute = function($attribute) {
var_dump($this->object);
};
return $this->object;
}//getContent
}//Class Contents
and I try to start the method via tis code
$contents->getContent(1);
$contents->object->getItemAttribute('titel');
But I keep getting the error "undefined method"
What am I doing wrong?
PHP is not Javascript. You cannot add methods to already existing instances of a class (or methods to an already-defined class, for that matter).
Here's some alternative ideas:
Use properties that are functions (that's in principle what you are doing now, just with a different invocation).
$object->getItemAttribute = function($a) {
return $object->{$a};
}
call_user_func($object->getItemAttribute);
I actually would not recommend implementing this, as it will probably make your code difficult to comprehend and annoy the hell out of any future maintainer (including yourself).
Define a wrapper class that implements your new functions:
class RequestWithAdditionalAttribute {
private $wrapped;
public function __construct(\stdClass $wrapped) {
$this->wrapped = $wrapped;
}
public function getItemAttribute($a) {
return $this->wrapped->{$a};
}
}
$wrappedObject = new RequestWithAdditionalAttribute($object)
PHP 7 variant: Create an anonymous class:
$wrappedObject = new class($object) {
private $wrapped;
public function __construct(\stdClass $wrapped) {
$this->wrapped = $wrapped;
}
public function getItemAttribute($a) {
return $this->wrapped->{$a};
}
};