Type of PHP hint at primitive values?

I would like to know if a type method can be introduced to expect primitive types?

Something like that:

public function someMethod(string $str) //^^^^^^ 

Or:

 private function anotherMethod(int $num) //^^^ 

same as you:

 private function otherMethod(Person $rambo) //^^^^^^ 

Is this possible in php?

+64
php primitive-types php-7 type-hinting
Apr 20 2018-11-11T00:
source share
8 answers

In PHP 7, they added the following:

Type declarations allow functions to require certain types to be specified during a call. If the specified value is of the wrong type, an error is generated: in PHP 5 this will be a recoverable fatal error, and PHP 7 will throw a TypeError exception.

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




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

PHP 5 introduces type hints. Functions can now force parameters to be objects (by specifying the class name in the function prototype), interfaces, arrays (starting with PHP 5.1) or called (starting from PHP 5.4) . However, if NULL is used as the default parameter value, it will be resolved as an argument for any subsequent call.

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

Tooltip types cannot be used with scalar types such as int or string. Not allowed and resources and traits.

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

+73
Apr 20 2018-11-11T00:
source share

Nope. You cannot enter hints for primitives because PHP has automatic conversions for primitives. See http://bugs.php.net/bug.php?id=29508 . This will never change if the PHP team has a sudden change of heart (which is doubtful, they are pretty stubborn).

+27
Apr 20 '11 at 1:50
source share

Yes, now it’s possible. After a long discussion, the proposal to introduce a type hint for scalar function parameters and return values ​​was only approved with the highest vote count, check in more detail:

A Scalar type hint consists of declaring function parameter types and return values, which can be of types int, float, string and bool. This allows the PHP runtime engine to check whether value types have been passed to parameter functions and returned values ​​have the expected types to detect possible programming errors. The hint type for objects, arrays, and callables is already allowed in previous versions of PHP. The current implementation introduces five new reserved words: int, float, bool, string and numeric. They were not previously reserved since casting is a special case in a 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_ERROR test("a"); // E_RECOVERABLE_ERROR test(""); // E_RECOVERABLE_ERROR test(1.5); // float(1.5) test(array()); // E_RECOVERABLE_ERROR test(new StdClass); // E_RECOVERABLE_ERROR 

You also have the option to declare to the source file, where you can enable the use of the Scaler type. It must be the 1st line of your script configuration and cannot be declared anywhere else in the same file.

 Like : declare(strict_types=1); 

At run time, when the PHP engine tries to return a value, it will check if it does not match it, as it is declared that it will generate a fatal error, for example, Fatal error: argument 1 passed to increment () must be of type integer, string given

Thanks to these new declaration functions, you can write more robust applications by detecting early programming errors caused by passing values ​​of the wrong types to functions.

Automatic type changes are also possible. For example, int types can automatically change in parameters of type float,

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

Return Type Declaration

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

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

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

A bit more complicated 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"); 

Weak type checking and type conversion behavior: weak type checking mode can be used with declaration statement (strict_types = 0); or lack of declaration of strict types. There are a few things to consider: Weak types of checked calls to an extension or built-in PHP function have the same behavior as in previous versions of PHP. Weak type checking rules for new scalar type declarations are basically the same as for extension functions or PHP built-in functions. NULL is a special case to match the current type declarations for classes, called and arrays. NULL is not accepted by default, unless it is a parameter and is explicitly set to NULL by default, for example: function sample (int $ a = NULL);

There are many advantages to this approach. You get type safety. This means that you can finally statically analyze the code! You may find errors when you accidentally take a string from one function and pass it as an integer to another. For me, a developer who uses PHP daily and sees Java as a reference for OOP languages, this is a big advance for PHP.

+14
Mar 23 '15 at 7:36
source share

Everyone has already said this, you cannot use the hint type for primitives because PHP doest does not support it. The reason for this is connected not only with automatic transformations, but also with the reaction of the community.

Until now, I remember that in May 2010, support for a scalar type entity was added to the PHP trunk. But due to community reactions, this feature wasn’t included in release 5.4.

There was a bit of controversy. Those who opposed the change argued that this support would run counter to fundamental PHP projects. PHP is considered a weak typed language. Essentially, this means that PHP does not require you to declare data types. Variables still have data types associated with them, but you can do radical things, such as adding a string to an integer without causing an error.

IMHO: The key type of hint should be added to PHP ASAP, this is the function we all need, I really respect that PHP is a weak typed language, but for development and production of a high level, especially for OO contexts, a hint of a scalar type is obligatory. We can have alternatives in PHP, as well as procedural and OO.

+5
Dec 27 '13 at 18:32
source share

Yes it is possible.

http://ru2.php.net/manual/ru/language.oop5.typehinting.php#83442

Warning: there is a typo in the original manual: res ro uce instead of res ou rce

People often ask about scalar / core types. Here is a drop in the class that I use in my MVC structure, which will allow you to enter key types using a special error handler.

Note. You must include this code above all other code in the include headers, and if you use the set_error_handler () function, you should know that this also uses it. You may need to bind set_error_handlers ()

Why?

  • Because people are tired of using is_ * functions to check parameters.
  • Reduce redundant coding of security encoders.
  • Functions / Methods are self-determination / documentation regarding the required input.

also .. Follow the type discussions in PHP 6.0 on PHP internal boards.

 <?php define('TYPEHINT_PCRE', '/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/'); class Typehint { private static $Typehints = array( 'boolean' => 'is_bool', 'integer' => 'is_int', 'float' => 'is_float', 'string' => 'is_string', 'resource' => 'is_resource' ); private function __Constrct() {} public static function initializeHandler() { set_error_handler('Typehint::handleTypehint'); return TRUE; } private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &$ThArgValue) { foreach ($ThBackTrace as $ThTrace) { // Match the function; Note we could do more defensive error checking. if (isset($ThTrace['function']) && $ThTrace['function'] == $ThFunction) { $ThArgValue = $ThTrace['args'][$ThArgIndex - 1]; return TRUE; } } return FALSE; } public static function handleTypehint($ErrLevel, $ErrMessage) { if ($ErrLevel == E_RECOVERABLE_ERROR) { if (preg_match(TYPEHINT_PCRE, $ErrMessage, $ErrMatches)) { list($ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType) = $ErrMatches; if (isset(self::$Typehints[$ThHint])) { $ThBacktrace = debug_backtrace(); $ThArgValue = NULL; if (self::getTypehintedArgument($ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue)) { if (call_user_func(self::$Typehints[$ThHint], $ThArgValue)) { return TRUE; } } } } } return FALSE; } } Typehint::initializeHandler(); ?> An are some examples of the class in use: <?php function teststring(string $string) { echo $string; } function testinteger(integer $integer) { echo $integer; } function testfloat(float $float) { echo $float; } // This will work for class methods as well. ?> 

You get an image.

+3
Jul 12 '15 at 4:42 on
source share

Accordind to PHP documentation tooltip type is not supported for primitive types.

It is supported for classes and interfaces.

Edit: I forgot to mention, which is also supported for arrays.

+1
Apr 20 '11 at 1:50
source share

Here is a short syntax for forcing a boolean to output from a passed parameter. If $state true, then $this->is_active set to true. All other value types are set to false.

 function set_active ( $state ) { $this->is_active = true === $state; } 
0
May 22 '15 at 15:46
source share

I think you do not need to introduce hints of PHP, because you are provided with type checking functions such as is_bool (), is_string (), etc. etc., so you can verify that you are trying to make an argument against these functions before actually making it an argument, although the method they use to check the array and types of objects will be much cleaner.

-2
Jul 17 '11 at 20:33
source share



All Articles