2

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?

2
  • and type object is not a string, (string)'bla', (object){any:1} Commented Feb 14, 2017 at 10:26
  • try function test(stdClass $arg){} Commented Feb 14, 2017 at 10:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I know how it works, I'm wondering why the keyword object even exists... When using it as a type hinting it doesn't refer to stdClass but when casting to a object it results in a stdClass... Why not just remove the keyword and cast to stdClass, and if they want to keep it, why allow it to be used as a type hinting when nothing will actually match?
Because you are allowed to make a class called object if you want. PHP does not know in advance what classes will be defined. The object becoming an stdClass is just how it works, you cast to an "object" and not a string for example.
That is even worse, that would mean that "object" means different things depending on if there is already a class named object or not. But thanks for the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.