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...
<?php
$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
?>
PHP.mk документација
settype
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
function.settype.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
function.settype.php
settype
Референца за `function.settype.php` со подобрена типографија и навигација.
settype
(PHP 4, PHP 5, PHP 7, PHP 8)
settype — Поставете го типот на променлива
Параметри
var-
Променливата што се конвертира.
type-
Можни вредности на
typeсе:- "boolean" или "bool"
- "integer" или "int"
- "float" или "double"
- "string"
- "array"
- "object"
- "null"
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.
Errors/Exceptions
Фрла ValueError ако вредноста на
type не е валиден тип, од PHP 8.0.0. Пред PHP 8.0.0, се емитуваше E_WARNING се емитуваше и false .
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
Сега фрла ValueError кога ќе се помине невалиден тип на type. Претходно,
E_WARNING беше емитувано и функцијата врати
false.
|
Примери
Пример #1 settype() example
<?php
$foo = "5bar"; // string
$bar = true; // boolean
settype($foo, "integer"); // $foo is now 5 (integer)
settype($bar, "string"); // $bar is now "1" (string)
var_dump($foo, $bar);
?>Белешки
Забелешка:
Максимална вредност за "int" е
PHP_INT_MAX.
Белешки од корисници 9 белешки
Специјални забелешки ¶
пред 14 години
robin на barafranca точка com ¶
пред 18 години
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.. ;)
sdibb на myway точка com ¶
пред 22 години
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:
<?
$number=ereg_replace("[^0-9]","",$number);
?>
nospamplease на veganismus точка ch ¶
20 години пред
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.
DarkMaster ¶
пред 4 години
<?php
/*
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
*/
$v = '12345';
$v = (int)$v;
$v = (string)$v;
?>
geoffsmiths на hotmail точка com ¶
пред 6 години
Please note:
When using settype to convert indexed arrays to objects, the properties of the typed object will be integers:
A brief example:
$a = ['1', '2'];
settype($a, 'object');
var_dump($a);
// output
object(stdClass)#1 (2) {
["0"]=>
string(1) "1"
["1"]=>
string(1) "2"
}
Анонимен ¶
пред 7 години
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.
<?php
// 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
int 1 Foo Object
(
)
Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10
float 1 Foo Object
(
)
array 1 Foo Object
(
)
object 1 Foo Object
(
)
Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14
unknowntype Foo Object
(
)
NULL 1 Foo Object
(
)
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() :
<?php
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.
Hope this helps ! :)
ns на canada точка com ¶
yasuo_ohgaki at hotmail dot com
This settype() behaviour seems consistent to me. Quoting two sections from the manual:
"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0]; // outputs 'ciao'
</pre>
And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:
"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."
It doesn't matter where the array counter is; values are added at the end, not at the counter.
matt на mattsoft точка net ¶
20 години пред
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.