Saruman
Saruman

Reputation: 153

PHP - type hinting for object, not the same as stdClass

Is it just me or is this behavior weird in PHP. Lets say for instance that we have a function like this:

function test(object $arg)
{}

If I were to call this function:

test((object)'string');

object (the type hinting) would not refer to a stdClass and would result in an error even though object seems to be a reference to stdClass when looking at the built in settype() function in PHP. Even casting to an object would result in a stdClass but for some reason I can't use settype($foo, 'stdClass')...

Is there a reason behind this?

Upvotes: 2

Views: 1116

Answers (1)

mcq8
mcq8

Reputation: 247

There is no overall object class definition in PHP. Even if you were to create a class called myClass and give an instance to the test function the code would not work. The typecast to object creates an instance of type stdClass.

You have to use function test(stdClass $arg) as the function definition.

Upvotes: 1

Related Questions