Jump to content

Type declaration (aka type hinting) for any object


NotionCommotion

Recommended Posts

Is it possible to declare a function parameter is an object, but not specify the instance of that object?  The following only allows stdClasses.  Reference http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

    protected function object_merge(\stdClass $obj,\stdClass $obj1)
    {
        foreach($obj1 as $key=>$property) {
            $obj->$key=$property;
        }
        return $obj;
    }
Link to comment
Share on other sites

I'd wrap the stdClass in your own class

class Whatever {

	private $data = [];

	public function __construct(\stdClass $source) {
		$this->data = get_object_vars($source);
	}

	public function merge($object) {
		if ($object instanceof self) {
			$this->data = array_merge($object->data);
		} else {
			$this->data = array_merge($this->data, get_object_vars($object));
		}
	}

}
and

$someObj = new Whatever($someObj);
$someObj->merge($addedObj);
Point is, avoid making static methods (oh: your object_merge() should be static since it doesn't use instance data) that operate on other objects. That sort of functionality should be dealt with in their respective classes.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.