Page 1 of 1

Datatype in function parameters?

Posted: Mon Apr 30, 2007 7:52 am
by Zu
PHP is a typeless language. However, in Zend Studio, if you write a function, for example...

Code: Select all

public function setRequired($field)
	{
	   $this -> _required[] = $field;
	}
...and then try and add a PHPDoc block to it, it comes up with...

Code: Select all

/**
	 * Enter description here...
	 *
	 * @param unknown_type $something
	 */
It is the 'unknown_type' which I am wondering about. Give the function parameters a type and you will get this:

Code: Select all

/**
    * Enter description here...
    *
    * @param string $something
    */
   private function setSomething(string $something)
   {
   	$this -> _something = $something;
   }
Which has got me wondering. Is Zend trying to slowly convince us to define the datatype we are passing around? We add the datatype if it is a Class object, so why not a "normal" variable?

I don't think I have ever seen a piece of PHP code that defines the data types; why is this?

Posted: Mon Apr 30, 2007 7:55 am
by feyd
So the code doesn't have to waste time checking type information before it can continue.

You can create class versions of the base types if you want to be type-strict.

Posted: Mon Apr 30, 2007 8:08 am
by superdezign
Besides, if you want to check types, there are multiple functions to do so. I always start functions with is_array, is_string and is_integer.

Posted: Mon Apr 30, 2007 8:25 am
by Maugrim_The_Reaper
There is no "string" type hint in PHP5 - only object types (classname) and "array" are supported. Presumably manual editing of the phpDoc comment does not add that "string" hint to the function parameter? All you'll get is a fatal error otherwise.

I'd assume the comment doesn't add type since "string" isn't a type hint and therefore the default parameter can be of any type, i.e. you would replace "unknown_type" with "mixed". If there is a specific type you want passed, then edit the comment for it and add the primitive check inside the method to enforce it.

Just be careful with Integers - since PHP is dynamically typed an is_int() check would prevent a stringified number from being passed. Which I suppose is why primitive type hinting in PHP doesn't offer as much value as the array/object types.

Posted: Mon Apr 30, 2007 11:57 am
by Begby
All that the phpdoc comment does is make make it so you get a visual type hint in Zend Studio (which is handy) and also it will add that type to your phpdoc generated files.

As was said though, all you can do currently is use objects for type hinting within the function statement. You can replace unkown in the docblock with string, or int, or bool, or nameOfMyFavoriteFood or whatever the hell you want, its just a free form value for use within docs and inline help.