settype

(PHP 4, PHP 5)

settypeПрисваивает переменной новый тип

Описание

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

Присваивает переменной var тип type.

Список параметров

var

Преобразуемая переменная.

type

Допустимыми значениями параметра type являются:

  • "boolean" (или, начиная с PHP версии 4.2.0, "bool")
  • "integer" (или, начиная с PHP версии 4.2.0, "int")
  • "float" (возможно только c PHP 4.2.0, для предыдущих версий используйте устаревший вариант "double")
  • "string"
  • "array"
  • "object"
  • "null" (начиная с PHP версии 4.2.0)

Возвращаемые значения

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

Примеры

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

<?php
$foo 
"5bar"// строка
$bar true;   // булевое значение

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

Примечания

Замечание:

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

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

Коментарии

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.
2000-05-05 19:38:07
http://php5.kiev.ua/manual/ru/function.settype.html
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);
?>
2003-09-07 01:03:15
http://php5.kiev.ua/manual/ru/function.settype.html
/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject(&$values) {
        $values = (object) $values;
        foreach ($values as $tkey => $val) {
            if (is_array($val)) {
                setobject($val);
                $values->$tkey = $val;
            }
        }
        return (bool) $values;
    }
2004-12-09 07:17:58
http://php5.kiev.ua/manual/ru/function.settype.html
Instead of settype you could use:
<?php

$int
=593// $int is a integer

$int.="";   // $int is now a string
2005-03-13 11:18:07
http://php5.kiev.ua/manual/ru/function.settype.html
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.
2005-07-22 10:38:08
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
note that settype() will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().

<?php
settype
($foo"integer");
echo(
"|$foo|");
?>

prints "|0|", NOT "||".

To get the latter, use:
<?php
if(isset($foo)) settype($foo"integer");
echo(
"|$foo|");
?>
2005-10-29 13:55:36
http://php5.kiev.ua/manual/ru/function.settype.html
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.
2005-12-06 23:49:03
http://php5.kiev.ua/manual/ru/function.settype.html
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func
2006-04-09 11:36:39
http://php5.kiev.ua/manual/ru/function.settype.html
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.. ;)
2008-03-05 06:20:50
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
In trying to convert an array of strings to an array of ints, 
I attempted to use settype with array_walk.

<?php
//$numArray is generated by another process
$numArray = array('13','14','33');

var_dump($numArray);

//my conversion function
function str_to_int($val){
 
//remember: settype($x, 'int') returns boolean (1=success, 0=failure)
  //--> so return $x to return new value
   
settype($val,'int');
    echo 
"<br />gettype = ".gettype($val)."<br />";
    return 
$val;
}

array_walk($numArray,'str_to_int');

var_dump($numArray);
?>

The var_dumps both return the following:
<?php
array(3) { [0]=> string(2"13" [1]=> string(2"14" [2]=> string(2"33" 
?>

The gettype echo will show the value as an integer.

So it seems that settype($val,'int') makes the conversion, 
but the function return value remains a string. 
Since settype returns a boolean, using 
<?php $val settype($val'int'); ?> 
is not a option.

I resolved my array value conversion using this instead:
<?php
$numArray 

     
array_map(create_function('$value''return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit. 

Also thanks to robin at barafranca dot com for 
pointing out the boolean return value of settype.
2008-11-17 11:38:14
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
settype() has some really strange, potentially buggy behavior.

As noted by Michael Benedict, using settype() on a variable will initialize that variable.  What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable.  So:

<?php
settype
($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.

<?php
$foo 
false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).

<?php
$foo 
true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
2010-04-19 02:59:48
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
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
?>
2012-02-26 02:00:42
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
any digit except 0 or -0 are considered true in boolean, and any string except '0' or '' are also considered true.

<?php

$foo 
'0';
settype($foo'boolean');
var_dump($foo); // false

$foo 0;
settype($foo'boolean');
var_dump($foo); // false
2016-11-10 19:31:40
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
$foo = "1";
settype($foo, "bool");
var_dump($foo); // Outputs: bool(true)

$bar = "0";
settype($bar, "bool");
var_dump($bar); // Outputs: bool(false)
2017-07-26 23:59:40
http://php5.kiev.ua/manual/ru/function.settype.html
Автор:
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($thisTRUE));
           
printf("%-20s %-20s %s\n"'int'settype($this'int'), print_r($thisTRUE));
           
printf("%-20s %-20s %s\n"'float'settype($this'float'), print_r($this));
           
printf("%-20s %-20s %s\n"'array'settype($this'array'), print_r($thisTRUE));
           
printf("%-20s %-20s %s\n"'object'settype($this'object'), print_r($thisTRUE));
           
printf("%-20s %-20s %s\n"'unknowntype'settype($this'unknowntype'), print_r($thisTRUE));
           
printf("%-20s %-20s %s\n"'NULL'settype($this'NULL'), print_r($thisTRUE));
           
printf("%-20s %-20s %s\n"'string'settype($this'string'), print_r($thisTRUE));
        }
    }
   
$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 !  :)
2019-01-04 15:41:56
http://php5.kiev.ua/manual/ru/function.settype.html

    Поддержать сайт на родительском проекте КГБ