62

I was trying to get my Netbeans to autocomplete with PHP, and I learned that this code is valid in PHP:

function blah(Bur $bur) {}

A couple of questions:

  1. Does this actually impose any limits on what type of variable I can pass to the blah method?
  2. If this is just to help the IDE, that's fine with me. How can I declare the type of a variable in PHP if I'm not in a function?
Community
  • 1
  • 1
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421

5 Answers5

84

This type-hinting only works for validating function arguments; you can't declare that a PHP variable must always be of a certain type. This means that in your example, $bur must be of type Bur when "blah" is called, but $bur could be reassigned to a non-Bur value inside the function.

Type-hinting only works for class or interface names; you can't declare that an argument must be an integer, for example.

One annoying aspect of PHP's type-hinting, which is different from Java's, is that NULL values aren't allowed. So if you want the option of passing NULL instead of an object, you must remove the type-hint and do something like this at the top of the function:

assert('$bur === NULL || $bur instanceof Bur');

EDIT: This last paragraph doesn't apply since PHP 5.1; you can now use NULL as a default value, even with a type hint.

EDIT: You can also install the SPL Type Handling extension, which gives you wrapper types for strings, ints, floats, booleans, and enums.

EDIT: You can also use "array" since PHP 5.1, and "callable" since PHP 5.4.

EDIT: You can also use "string", "int", "float" and "bool" since PHP 7.0.

EDIT: As of PHP 7.4, you can declare member variables of a class/interface/trait as a specific type like public int $a;, and variables that are declared this way cannot be assigned to a value of another type. You can also use union types such as string|int as of PHP 8.0, and you can use classes in the union types as of PHP 8.1.

https://www.php.net/manual/en/language.types.declarations.php

mbomb007
  • 3,788
  • 3
  • 39
  • 68
JW.
  • 50,691
  • 36
  • 115
  • 143
  • 4
    Complete and great answer. I'll admit that my main focus was to get my IDE hinting, which I have already figured out here http://stackoverflow.com/questions/390192... personally, I find that many aspects of PHP are depressing hacks, but that's just my preference for typed langs. – Dan Rosenstark Dec 24 '08 at 20:09
  • 4
    There there, even those of us who don't prefer strongly-typed languages agree with you :) – J Cooper Dec 24 '08 at 21:20
  • 4
    A good step for PHP would be the option to declare type or leave it to be dynamic. I hope to see that in future PHP – Dr Casper Black Mar 04 '11 at 15:46
  • I slightly disagree or want to make more precise the first EDIT: null is never of valid type $myClass (PHP 5.3). Perhaps it works as default param, but one still can't pass it in (like in Java) if a type hint in function signature are used. – Frank N Jul 03 '12 at 09:16
  • 2
    Actually you can declare `myFunc(MyClass $x = NULL)`, and then call `myFunc(NULL)` or `myFunc()` without an error. – JW. Jul 03 '12 at 14:47
  • Not allowing `null` for type hinted parameters by default is something that I really like. As you say, Java allows this and they are now screwing around with `@Nullable` and `@NotNull`. I think the PHP implementation helps a lot to prevent null reference errors. – MazeChaZer Jul 07 '16 at 10:52
  • PHP 7.2 adds `object` as well – Jonathan Mar 02 '18 at 19:10
  • Too bad you can't specify an array of objects e.g.: `functionName(int[] $someIds)` or `functionName(SomeObject[] $someObjects)`, but there is partial workaround: https://stackoverflow.com/a/34273821/448816 – mikhail-t Aug 01 '18 at 21:29
  • For allowing null values, you can also do `function blah(?Bur $bur) {}` (note the `?` in front of `Bur`). See https://stackoverflow.com/a/38129401/4284627. – Donald Duck Jun 25 '19 at 21:57
42
  1. Specifying a data type for a function parameter will cause PHP to throw a catchable fatal error if you pass a value which is not of that type. Please note though, you can only specify types for classes, and not primitives such as strings or integers.
  2. Most IDE's can infer a data type from a PHPDoc style comment if one is provided. e.g.

/**
 * @var string
 */
public $variable = "Blah";

UPDATE 2021: As of PHP 7 (which is several years old at this point) primitive types can also be declared for function arguments. Nullability can also be indicated with a ? in front of the type from 7.1 onward. You can declare return types now too. So this is valid PHP these days:

public function hasFoo(?int $numFoos) :bool {

phpStorm (my current preferred IDE) is happy to use all of these types for code completion, so I don't need as many phpDoc comments for typing as I used to.

Jim OHalloran
  • 5,859
  • 2
  • 37
  • 57
  • what if I'm not in a class? The $variable is coming from an included PHP... I think I'm almost where I need to be... – Dan Rosenstark Dec 24 '08 at 07:13
  • No need to test. According to the PHP docs "Failing to satisfy the type hint results in a catchable fatal error." http://ch2.php.net/language.oop5.typehinting – Dan Rosenstark Dec 24 '08 at 16:26
  • i confirm, it works perfectly with eclipse PDT, thanks for the "Most IDE's can infer... " mention. – TheFuquan Dec 17 '15 at 21:42
8

It's called type hinting, added with PHP 5. It isn't quite what you may be expecting if you are coming from a language like Java. It does cause an error to be thrown if you don't pass in the expected type. You can't type-hint primitives, though (no int $bur).

J Cooper
  • 16,891
  • 12
  • 65
  • 110
7

#2 : (...) How can I declare the type of a variable in PHP if I'm not in a function?

I recently heard about "settype()" and "gettype()" in PHP4 & 5
You can force the variable type anytime easily


From PHP.net :

bool settype ( mixed &$var , string $type )

Parameters

var : The variable being converted. type : Possibles values of type are:

  • "boolean" (or, since PHP 4.2.0, "bool")
  • "integer" (or, since PHP 4.2.0, "int")
  • "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
  • "string"
  • "array"
  • "object"
  • "null" (since PHP 4.2.0)

[ :D First visit, first comment...]

Shad
  • 71
  • 2
  • Yeah I just saw that. settype and gettype are only for primitives, which doesn't help (although technically it does answer the question, so I'll vote you up. Please provide a link to the PHP doc and remove it from your answer). – Dan Rosenstark Dec 24 '08 at 15:29
  • `$myVar=(string) $variabel;` gives a string Variable. Afterwards, assign a value. – Nick Oetjen Sep 24 '20 at 16:10
3

Does this actually impose any limits on what type of variable I can pass to the blah method?

This is called type hinting. According to the PHP documentation that I just linked to, yes, it does impose limits on the argument type: "Failing to satisfy the type hint results in a catchable fatal error."

How can I declare the type of a variable in PHP if I'm not in a function?

Read type juggling. You can't explicitly define a variable's type in PHP, its type is decided by the context it is used in.

Paige Ruten
  • 172,675
  • 36
  • 177
  • 197