user1046463
user1046463

Reputation: 13

PHP function with space-separated arguments

What does it mean in PHP when a function's list of arguments contains a class and variable name separated by a space?

For example, in the Batchbook API sample PHP library, there is the following function declaration:

public function postPerson(Batchblue_Service_BatchBook_Person $person)

where Batchblue_Service_Batchbook_Person is a class and $person is an instance of that class.

Upvotes: 1

Views: 276

Answers (2)

GargantuChet
GargantuChet

Reputation: 5789

A comment in PHP's page on function arguments provides some hint.

To quote:

You can use (very) limited signatures for your functions, specifing type of arguments allowed.

For example:

public function Right( My_Class $a, array $b )

tells first argument have to by object of My_Class, second an array. My_Class means that you can pass also object of class that either extends My_Class or implements (if My_Class is abstract class) My_Class. If you need exactly My_Class you need to either make it final, or add some code to check what $a really.

Also note, that (unfortunately) "array" is the only built-in type you can use in signature. Any other types i.e.:

public function Wrong( string $a, boolean $b )

will cause an error, because PHP will complain that $a is not an object of class string (and $b is not an object of class boolean).

So if you need to know if $a is a string or $b bool, you need to write some code in your function body and i.e. throw exception if you detect type mismatch (or you can try to cast if it's doable).

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

That is type hinting. It means you are saying that that argument has to be an instance of that class or one of its descendent classes.

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Upvotes: 5

Related Questions