Php define type string

settype

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования settype()

$foo = «5bar» ; // строка
$bar = true ; // булевое значение

settype ( $foo , «integer» ); // $foo теперь 5 (целое)
settype ( $bar , «string» ); // $bar теперь «1» (строка)
?>

Примечания

Замечание:

Максимальное значение для «int» равно PHP_INT_MAX .

Смотрите также

User Contributed Notes 17 notes

Note that you can’t use this to convert a string ‘true’ or ‘false’ to a boolean variable true or false as a string ‘false’ is a boolean true. The empty string would be false instead.

$var = «true» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // true

$var = «false» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // true as well!

$var = «» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // false
?>

Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable — so:

$blah = settype($blah, «int»); // is wrong, changes $blah to 0 or 1
settype($blah, «int»); // is correct

Hope this helps someone else who makes a mistake.. 😉

Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins. The function intval($string) does the same thing.

If you’re looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes), try this instead:

you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.

/*
This example works 4x faster than settype() function in PHP-CGI 5.4.13 and
8x faster in PHP-CGI 7.1.3(x64) for windows
*/

If you attempt to convert the special $this variable from an instance method (only in classes) :
* PHP will silently return TRUE and leave $this unchanged if the type was ‘bool’, ‘array’, ‘object’ or ‘NULL’
* PHP will generate an E_NOTICE if the type was ‘int’, ‘float’ or ‘double’, and $this will not be casted
* PHP will throw a catchable fatal error when the type is ‘string’ and the class does not define the __toString() method
Unless the new variable type passed as the second argument is invalid, settype() will return TRUE. In all cases the object will remain unchanged.
// This was tested with PHP 7.2
class Foo function test () printf ( «%-20s %-20s %s\n» , ‘Type’ , ‘Succeed?’ , ‘Converted’ );

// settype() should throw a fatal error, as $this cannot be re-assigned
printf ( «%-20s %-20s %s\n» , ‘bool’ , settype ( $this , ‘bool’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘int’ , settype ( $this , ‘int’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘float’ , settype ( $this , ‘float’ ), print_r ( $this ));
printf ( «%-20s %-20s %s\n» , ‘array’ , settype ( $this , ‘array’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘object’ , settype ( $this , ‘object’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘unknowntype’ , settype ( $this , ‘unknowntype’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘NULL’ , settype ( $this , ‘NULL’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘string’ , settype ( $this , ‘string’ ), print_r ( $this , TRUE ));
>
>
$a = new Foo ();
$a -> test ();
?>
Here is the result :
Type Succeed? Converted
bool 1 Foo Object
(
)

Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9

Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10

Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14

Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15

If the class Foo implements __toString() :
class Foo // .
function __toString () return ‘Foo object is awesome!’ ;
>
// .
>
?>
So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString() method.

Источник

Php define type string

While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.

PHP 5.6 added the splat operator (. ) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.

function typeArrayNullInt (? int . $arg ): void >

function doSomething (array $ints ): void (function (? int . $arg ) <>)(. $ints );
// Alternatively,
( fn (? int . $arg ) => $arg )(. $ints );
// Or to avoid cluttering memory with too many closures
typeArrayNullInt (. $ints );

function doSomethingElse (? int . $ints ): void /* . */
>

$ints = [ 1 , 2 , 3 , 4 , null ];
doSomething ( $ints );
doSomethingElse (. $ints );
?>

Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething’s method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.

If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.

same data type and same value but first function declare as a argument type declaration and return int(7)
and second fucntion declare as a return type declaration but return int(8).

function argument_type_declaration(int $a, int $b) return $a+$b;
>

function return_type_declaration($a,$b) :int return $a+$b;
>

Источник

Читайте также:  Accessing http headers javascript
Оцените статью