Jump to content

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;
    }

Not yet: "object" will be available in 7.2.

 

But I'm skeptical that you should be allowing any object. What about ones that implement __get/set? I'm pretty sure your method is only designed to work on particular sorts of objects...

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.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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