PHP type-hinting to primitive values? PHP type-hinting to primitive values? php php

PHP type-hinting to primitive values?


In PHP 7 they added the following:

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

Reference:http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration


When this answer was asked, PHP 5 was the latest and said the following:

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), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

If class or interface is specified as type hint then all its children or implementations are allowed too.

Type hints cannot be used with scalar types such as int or string. Resources and Traits are not allowed either.

Reference: http://php.net/manual/en/language.oop5.typehinting.php


Nope. You can't type hint for primitives because PHP has automatic conversions for primitives. See http://bugs.php.net/bug.php?id=29508. This will never change, unless the PHP team has a sudden change of heart (which is doubtful, they're pretty stubborn).


Yes, Now its possible,After a long discussion, a proposal to implement type hinting for scalar function parameters and return values was just approved with the highest vote count so far, check for details :

Scalar type hinting consists of declaring the types of function parameters and return values that can be of the types int, float, string and bool.This allows the PHP runtime engine to check if the types of values passed to parameter functions and return values are of the expected types in order to detect eventual programming mistakes.Type hinting for objects, arrays and callables was already allowed in past PHP versions.The current implementation introduces five new reserved words: int, float, bool, string and numeric. These were not previously reserved, because casting is a special case in the lexer.

Example :function test(float $a) {    var_dump($a); }test(1); // float(1)test("1"); // float(1)test(1.0); // float(1)test("1a"); // E_RECOVERABLE_ERRORtest("a"); // E_RECOVERABLE_ERRORtest(""); // E_RECOVERABLE_ERRORtest(1.5); // float(1.5)test(array()); // E_RECOVERABLE_ERRORtest(new StdClass); // E_RECOVERABLE_ERROR

You have also an option to declare into source file where you can allow Scaler type hinting.It must be 1st line of your config script and can’t be declared elsewhere in the same file.

Like : declare(strict_types=1);

At runtime, when the PHP engine tries to return a value, it will check if doesn’t match as declared it will throw a fatal error like,Fatal error: Argument 1 passed to increment() must be of the type integer, string given

With this new features of declaration, you can write more robust applications by detecting early programming mistakes caused by passing values of the wrong types to functions.

Automatic changes of types may also happen. For example, int types can be change into float type parameters automatically,

function test(float $x){    var_dump($x);}test(10); // works fine

Declaring the Return Type

We can declare the return types adding a colon followed by the expected type between the last parenthesis and the first bracket in the function declaration.

For functions that do not return any value, nothing should be added in the return type declaration section.

function mustReturnInt(): int { ... }function mustReturnString(): string { ... }function mustReturnBool(): bool { ... }function mustReturnFloat(): float { ... }function doesNotReturnAnything() { ... }

A Little Bit more Complex Example

declare(strict_types=1);  class StrictTypesTestingClass {  public function returnSameInt(int $value): int {   return $value;  }   public function returnSameFloat(float $value): float {   return $value;  }  public function returnSameString(string $value): string {   return $value;  }   public function returnSameBool(bool $value): bool {   return $value;  } }  $check = new StrictTypesTestingClass();  // calls that work  print $check->returnSameInt(10); print $check->returnSameFloat(10.0); print $check->returnSameString("test"); print $check->returnSameBool(true) ? 'true' : 'false';  // calls that throw exceptions print $check->returnSameInt("10"); print $check->returnSameFloat("10.0"); print $check->returnSameString(10);print $check->returnSameBool("true");

Behavior of Weak Type Checking and Type Conversion : The weak type checking mode can be used with the statement declare(strict_types=0); or the absence of the strict types declaration. There are a few of points to take into account:Weak type checked calls to an extension or built-in PHP function have the same behaviour as in previous PHP versionsThe weak type checking rules for new scalar type declarations are mostly the same as those of extension or built-in PHP functions.NULL is a special case in order to be consistent with the current type declarations for classes, callables and arrays. NULL is not accepted by default, unless it is a parameter and is explicitly given a default value of NULL, for instance: function sample(int $a = NULL);

There are a lots of advantages to this approach. You get type safety. Which means that you can finally statically analyze code! You can detect bugs where you accidentally take a string from one function and pass it as an integer to another.For me, a developer that uses PHP on a daily basis and sees Java as a reference for OOP languages, this is great progress for PHP.