Learning PHP, have a question about passing data to a function or class

Ok, I am learning about PHP and things like namespaces. Anyway, I came across this example and wanted to know what exactly it is doing:

function test(\foo\MyClass $typehintexample = null) {}

To me, it looks like a function called test that expects some data being passed to it. But Im used to seeing something like:

function test($typehintexample = null) {}

So what is it doing passing the name space \foo\MyClass? Is that passing the reference to MyClass under the foo namespace? So inside the test function I would be able to access methods from the MyClass class? If so, why does it have $typehintexample = null next to it?

What you see here is called type hinting. By using this syntax, you tell the function what kind of argument to expect. In human terms, this means:

“You might be getting an argument, and if you do, it will be an instance of the class \foo\MyClass”.

The “null” part makes sure the argument is optional - you can pass it to the function, but you don’t have to, and if you don’t, it will default to null.

This also means that you won’t be able to pass anything other than an instance of \foo\MyClass into the function. If you do any of the following:

test(5);
test("five");
test([1, 2, 3, 4, 5]);

You’ll get an error.

If you do:

$instance = new \foo\MyClass();
test($instance);

it’ll be fine.

2 Likes

Ahh, ok its type casting. Got it, so $typehintexample is expected to be a instance of the myclass class and it not it is null. Got it, so inside that function we can access the method of myclass via the variable $typehintexample, correct?

Thanks for the easy explanation!

You got it, that’s correct. You’re welcome!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.