型の相互変換

PHP は変数宣言時に明示的な型定義を必要としません。 型を定義しない場合、変数の型は保存する値によって決まります。 これは、変数 $var に文字列を代入した場合、 $var の型は文字列 (string) になることを意味しています。 その後、整数値を $var に代入すると、 その変数の型は整数 (int) になります。

コンテクスト(文脈)によっては、 PHP が値を別の型に自動変換しようとすることがあります。 自動変換が行われる異なるコンテクストが存在するのは、以下のとおりです:

  • 数値のコンテクスト
  • 文字列のコンテクスト
  • 論理コンテクスト
  • 整数と文字列のコンテクスト
  • 比較のコンテクスト
  • 関数のコンテクスト

注意: 値を別の型として解釈する必要がある場合でも、 値そのものの型は 変わりません

変数を強制的にある特定の型として評価させたい場合は、 型キャスト のセクションを参照ください。 ある変数の型を変更したい場合は、settype() を参照ください。

数値のコンテクスト

これは、 算術演算子 を使った場合です。

このコンテクストでは、 オペランドのどちらかが float (または整数と解釈できない場合) の場合か、 両方のオペランドが float の場合、 結果の型は float になります。 そうでない場合、オペランドは整数として解釈され、 結果の型も整数になります。 PHP 8.0.0 以降では、いずれかのオペランドが解釈できない場合、 TypeError がスローされます。

文字列のコンテクスト

これは、 echo, print文字列中の変数のパース、または 文字列演算子 を使った場合です。

値は文字列として解釈されます。 文字列として解釈できない場合、 TypeError がスローされます。 PHP 7.4.0 より前のバージョンでは、 E_RECOVERABLE_ERROR が発生していました。

論理コンテクスト

これは、 制御構文や 三項演算子, 論理演算子 を使った場合です。

値は論理値 (bool) として解釈されます。

整数と文字列のコンテクスト

これは、 ビット演算子 を使った場合です。

全てのオペランドが文字列の場合、 結果の型も文字列になります。 そうでない場合、 オペランドは整数として解釈され、 結果の型も整数になります。 PHP 8.0.0 以降では、いずれかのオペランドが解釈できない場合、 TypeError がスローされます。

比較のコンテクスト

これは、 比較演算子 を使った場合です。

このコンテクストで発生する型変換については、 さまざまな型の比較表 に説明があります。

関数のコンテクスト

これは、値が型付きの引数、型付きプロパティに渡された場合や、 戻り値の型を宣言している関数から値が返される場合です。

このコンテクストでは、値はその型の値でなければなりません。 これにはふたつ例外があります。 ひとつめは値の型が int で、 宣言されている型が float の場合、 整数が浮動小数点に変換されることです。 ふたつめは型が スカラー型、 または値がスカラー型に変換可能な場合で、 かつ型の自動変換モードが有効な場合(デフォルト)、 スカラー型の値だけが別の変換可能なスカラー型に変換される可能性があることです。 この振る舞いに関する詳細は、以下を参照ください:

警告

内部関数 は、null を自動的にスカラー型に変換します。 この振る舞いは PHP 8.1.0 以降は 推奨されなくなっています

単一の型宣言における、型の自動変換

  • 論理型(bool) が宣言されている場合: 値は bool として解釈されます。
  • 整数型 (int) が宣言されてい場合: int への変換が定義されている場合は、int として解釈されます。たとえば、文字列が 数値形式 である場合です。
  • float が宣言されている場合: float への変換が定義されている場合は、float として解釈されます。たとえば、文字列が 数値形式 である場合です。
  • 文字列 (string) 型として宣言されている場合: 値は文字列として解釈されます。

union 型と型の自動変換

strict_types が有効になっていない場合、 スカラー型の宣言は、限られた暗黙の型変換が行われます。 値の正確な型が union の一部に指定されていない場合、 次の順に対象となる型が選択されます:

  1. int
  2. float
  3. string
  4. bool
正確な型が union の中に存在し、 かつ値が PHP の既存の型チェックのセマンティクスによって型変換できる場合、 その型が選択されます。 そうでない場合、次の型を試そうとします。

警告

例外として、値が文字列で、int と float が union に含まれていた場合、 型は既存の 数値形式の文字列 を解釈するセマンティクスによって決まります。 たとえば、"42" の場合、 int が選ばれますし、 "42.0" の場合、float が選ばれます。

注意:

上のリストに入っていない型については、 暗黙の型変換が行われる対象ではありません。 特に、暗黙のうちに null, false, true に変換されることはありません。

例1 union の型のひとつに変換される例

<?php
// int|string
42 --> 42 // 正確に型が一致
"42" --> "42" // 正確に型が一致
new ObjectWithToString --> "Result of __toString()"
// オブジェクトは int と互換性がないので、文字列にフォールバック
42.0 --> 42 // float は int と互換性がある
42.1 --> 42 // float は int と互換性がある
1e100 --> "1.0E+100" // int には大きすぎる float なので、文字列にフォールバック
INF --> "INF" // int には大きすぎる float なので、文字列にフォールバック
true --> 1 // bool は int と互換性がある
[] --> TypeError // 配列はint, string と互換性はない。
// int|float|bool
"45" --> 45 // int の数値形式の文字列
"45.0" --> 45.0 // float の数値形式の文字列
"45X" --> true // 数値形式の文字列ではない。boolにフォールバック
"" --> false // 数値形式の文字列ではない。boolにフォールバック
"X" --> true // 数値形式の文字列ではない。boolにフォールバック
[] --> TypeError // 配列はint, float, bool と互換性はない。
?>

型キャスト

型キャストは、変換しようとする型の名前を括弧で括り、 キャストする変数の前に置くことで、値を別の型に変換するものです。

<?php
$foo
= 10; // $foo は整数です
$bar = (bool) $foo; // $bar は boolean です
?>

使用可能なキャストを以下に示します:

  • (int) - 整数(int) へのキャスト
  • (bool) - 論理値(bool) へのキャスト
  • (float) - float へのキャスト
  • (string) - 文字列(string) へのキャスト
  • (array) - 配列(array) へのキャスト
  • (object) - オブジェクト(object) へのキャスト
  • (unset) - NULL へのキャスト

注意:

(integer) は、(int) のエイリアスです。 (boolean) は、(bool) のエイリアスです。 (binary) は、(string) のエイリアスです。 (double)(real) は、(float) のエイリアスです。 これらのキャストは、正規化された型の名前を使っていません。そのため使うこと自体がおすすめできません。

警告

キャストのエイリアス (real) を使うことは、PHP 8.0.0 以降は推奨されなくなっています。

警告

(unset) によるキャストは、 PHP 7.2.0 以降推奨されなくなりました。 (unset) によるキャストは、 値に NULL 値を代入することと同じです。 (unset) によるキャストは、PHP 8.0.0 で削除されました。

警告

将来サポートされることを見越して、(binary) によるキャストと b プレフィックスが存在しています。 (binary)(string) は現状は等価ですが、将来変更される可能性があります。そのため、現状等価であることに依存すべきではありません。

注意:

キャストの括弧内のホワイトスペースは無視されます。 よって、以下のふたつのキャストは等価です:

<?php
$foo
= (int) $bar;
$foo = ( int ) $bar;
?>

以下の例は、リテラル文字列や変数を、バイナリ文字列にキャストします:

<?php
$binary
= (binary) $string;
$binary = b"binary string";
?>

注意: ある変数を文字列にキャストする代わりに、 二重引用符で括ることもできます。

<?php
$foo
= 10; // $foo は整数です
$str = "$foo"; // $str は文字列です
$fst = (string) $foo; // $fst も文字列です

// これは、"they are the same"を出力します
if ($fst === $str) {
echo
"they are the same";
}
?>

型の間でキャストを行う際の動作は、必ずしも明確ではありません。 詳細については、以下の節を参照ください:

注意: PHP では配列の添字と同じ構文を使用した文字列へのアクセスをサポートしているので、次の例はあらゆるバージョンの PHP で成立します:

<?php
$a
= 'car'; // $a は文字列です
$a[0] = 'b'; // $a はここでも文字列です
echo $a; // bar
?>
詳細は、 文字列への文字単位のアクセス を参照ください。

add a note add a note

User Contributed Notes 36 notes

up
70
Raja
19 years ago
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
up
12
Anonymous
5 years ago
"An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is."

I understand what the doc is trying to say here, but this sentence is not correct as stated, other types can be coerced into floats.

e.g.

<?php
$a
= "1.5"; // $a is a string
$b = 100; // $b is an int
$c = $a * $b; // $c is a float, value is 150
// multiplication resulted in a float despite fact that neither operand was a float
up
26
yury at krasu dot ru
21 years ago
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
up
22
fardelian
11 years ago
Casting objects to arrays is a pain. Example:

<?php

class MyClass {

    private
$priv = 'priv_value';
    protected
$prot = 'prot_value';
    public
$pub = 'pub_value';
    public
$MyClasspriv = 'second_pub_value';

}

$test = new MyClass();
echo
'<pre>';
print_r((array) $test);

/*
Array
(
    [MyClasspriv] => priv_value
    [*prot] => prot_value
    [pub] => pub_value
    [MyClasspriv] => second_pub_value
)
*/

?>

Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true:

<?php

foreach ((array) $test as $key => $value) {
   
$len = strlen($key);
    echo
"{$key} ({$len}) => {$value}<br />";
    for (
$i = 0; $i < $len; ++$i) {
        echo
ord($key[$i]) . ' ';
    }
    echo
'<hr />';
}

/*
MyClasspriv (13) => priv_value
0 77 121 67 108 97 115 115 0 112 114 105 118
*prot (7) => prot_value
0 42 0 112 114 111 116
pub (3) => pub_value
112 117 98
MyClasspriv (11) => second_pub_value
77 121 67 108 97 115 115 112 114 105 118
*/

?>

The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this.
up
19
Anonymous
21 years ago
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!
up
10
rmirabelle
13 years ago
The object casting methods presented here do not take into account the class hierarchy of the class you're trying to cast your object into.

/**
     * Convert an object to a specific class.
     * @param object $object
     * @param string $class_name The class to cast the object to
     * @return object
     */
    public static function cast($object, $class_name) {
        if($object === false) return false;
        if(class_exists($class_name)) {
            $ser_object     = serialize($object);
            $obj_name_len     = strlen(get_class($object));
            $start             = $obj_name_len + strlen($obj_name_len) + 6;
            $new_object      = 'O:' . strlen($class_name) . ':"' . $class_name . '":';
            $new_object     .= substr($ser_object, $start);
            $new_object     = unserialize($new_object);
            /**
             * The new object is of the correct type but
             * is not fully initialized throughout its graph.
             * To get the full object graph (including parent
             * class data, we need to create a new instance of
             * the specified class and then assign the new
             * properties to it.
             */
            $graph = new $class_name;
            foreach($new_object as $prop => $val) {
                $graph->$prop = $val;
            }
            return $graph;
        } else {
            throw new CoreException(false, "could not find class $class_name for casting in DB::cast");
            return false;
        }
    }
up
2
Dhairya Lakhera
4 years ago
Value of uninitialized variable of different data types.

settype($a,'bool');
var_dump($a);         //boolean false

settype($b,'string');
var_dump($b);        //string '' (length=0)

settype($c,'array');
var_dump($c);        //array (size=0)  empty

settype($d,'int');
var_dump($d);       //int 0

settype($e,'float');
var_dump($e);      //float 0

settype($f,'object');
var_dump($f);     //object(stdClass)[1]
up
11
ieee at REMOVE dot bk dot ru
11 years ago
There are some shorter and faster (at least on my machine) ways to perform a type cast.
<?php
$string
='12345.678';
$float=+$string;
$integer=0|$string;
$boolean=!!$string;
?>
up
5
kuzawinski dot marcin at NOSPAM dot gmail dot com
9 years ago
You REALLY must be aware what you are doing, when you cast a lot  in your code. For example, you can accidentaly change FALSE to TRUE  (probably not in one line, like here):

if(TRUE === (boolean) (array) (int) FALSE) {
    kaboom();
}
up
2
Anonymous
12 years ago
namaroulis stated "I found it tricky to check if a posted value was an integer"; to test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric():

<?php
$_POST
['a'] = "42";

is_numeric( $_POST['a'] ); // true
?>
up
2
martinscotta at gmail dot com
13 years ago
in response to bhsmither at gmail.com

It raises a warning because of the bad enquoted variable

<?php

error_reporting
( E_ALL | E_STRICT );

$foo['ten'] = 10;        // $foo['ten'] is an array holding an integer at key "ten"
$str = "{$foo['ten']}"// works "10"
$str = "$foo[ten]";      // DO NOT work!
up
2
wbcarts at juno dot com
15 years ago
WHERE'S THE BEEF?

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point {
  protected
$x, $y;

  public function
__construct($xVal = 0, $yVal = 0) {
   
$this->x = $xVal;
   
$this->y = $yVal;
  }
  public function
getX() { return $this->x; }
  public function
getY() { return $this->y; }
}

$p = new Point(25, 35);
echo
$p->getX();      // 25
echo $p->getY();      // 35
?>
Ok, now we need extra powers. PHP gives us several options:
  A. We can tag on extra properties on-the-fly using everyday PHP syntax...
    $p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.
  B. We can try type-casting it to a different type to access more functions...
    $p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.
  C. Do it the right way using OOP - and just extend the Point class already.
<?php
class Point3D extends Point {
  protected
$z;                                // add extra properties...

 
public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {
   
parent::__construct($xVal, $yVal);
   
$this->z = $zVal;
  }
  public function
getZ() { return $this->z; }  // add extra functions...
}

$p3d = new Point3D(25, 35, 45);  // more data, more functions, more everything...
echo $p3d->getX();               // 25
echo $p3d->getY();               // 35
echo $p3d->getZ();               // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
up
2
edgar dot klerks at gmail dot com
15 years ago
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

Without cast:

<?php

$hello
= 'Hello world';
print
$hello;
unset(
$hello);

?>

With the unset cast:

<?php

$hello
= 'Hello world';
$hello = (unset) print $hello;

?>

Hoorah, we lost another line!
up
2
miracle at 1oo-percent dot de
18 years ago
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.

e.g.

$val = 0 + "1.234";
(type of $val is float now)

$val = 0 + "123";
(type of $val is integer now)
up
2
Anonymous
13 years ago
Checking for strings to be integers?
How about if a string is a float?

<?php

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt);

echo
'Is Integer? ',  ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n";

/* checks if a string is an integer with no whitespace before or after  */
$isInt=preg_match('/^[0-9]+$/', $myString);

echo
'Is Integer? ',  ($isInt) ? 'Yes' : 'No', "\n";

/* When checking for floats, we assume the possibility of no decimals needed.  If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
[0-9]+(\.[0-9]+)?
with
[0-9]+\.[0-9]+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum);

echo
'Is Number? ',  ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n";

/* checks if a string is a float with no whitespace before or after */
$isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString);

echo
'Is Number? ',  ($isFloat) ? 'Yes' : 'No', "\n";

?>
up
2
Anonymous
3 years ago
Cast operators have a very high precedence, for example (int)$a/$b is evaluated as ((int)$a)/$b, not as (int)($a/$b) [which would be like intdiv($a,$b) if both $a and $b are integers].
The only exceptions (as of PHP 8.0) are the exponentiation operator ** [i.e. (int)$a**$b is evaluated as (int)($a**$b) rather than ((int)$a)**$b] and the special access/invocation operators ->, ::, [] and () [i.e. in each of (int)$a->$b, (int)$a::$b, (int)$a[$b] and (int)$a($b), the cast is performed last on the result of the variable expression].
up
1
lucazd at gmail dot com
15 years ago
@alexgr (20-Jun-2008)

Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:

<?php
class MyObject {
   
/**
     * @param MyObject $object
     * @return MyObject
     */
   
static public function cast(MyObject $object) {
        return
$object;
    }
   
/** Does nothing */
   
function f() {}
}

class
X extends MyObject {
   
/** Throws exception */
   
function f() { throw new exception(); }
}

$x = MyObject::cast(new X);
$x->f(); // Your IDE tells 'f() Does nothing'
?>

However, when you run the script, you will get an exception.
up
1
namaroulis at gmail dot com
13 years ago
I found it tricky to check if a posted value was an integer.

<?php

$_POST
['a'] = "42";

is_int( $_POST['a'] ); //false
is_int( intval( "anything" ) ); //always true
?>

A method I use for checking if a string represents an integer value.

<?php
function check_int( $str )
                {
                    return 
is_numeric( $str ) && intval( $str ) - $str == 0;
                }
?>
up
1
jphansen at uga dot edu
12 years ago
Type casting from string to int and vice versa is probably the most common conversation. PHP does this very simply through the +. and .= operators, removing any explicit casting:

<?php
$x
= 1;
var_dump($x); // int(1)
$x .= 1;
var_dump($x); // string(2) "11"; also an empty string ("") would cast to string without changing $x

$x = "1";
var_dump($x);  // string(1) "1"
$x += 1;
var_dump($x); // int(2); also a zero value (0) would cast to int without changing $x
?>
up
1
Anonymous
18 years ago
If you have a boolean, performing increments on it won't do anything despite it being 1.  This is a case where you have to use a cast.

<html>
<body> <!-- don't want w3.org to get mad... -->
<?php
$bar
= TRUE;
?>
I have <?=$bar?> bar.
<?php
$bar
++;
?>
I now have <?=$bar?> bar.
<?php
$bar
= (int) $bar;
$bar++;
?>
I finally have <?=$bar?> bar.
</body>
</html>

That will print

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
up
0
hemi68 at hotmail dot com
12 years ago
Cast a string to binary using PHP < 5.2.1

$binary = unpack('c*', $string);
up
0
bhsmither at gmail.com
14 years ago
<?php
$foo
['ten'] = 10;            // $foo['ten'] is an array holding an integer at key "ten"
$str = "$foo['ten']";        // throws T_ENCAPSED_AND_WHITESPACE error
$str = "$foo[ten]";          // works because constants are skipped in quotes
$fst = (string) $foo['ten']; // works with clear intention
?>
up
0
hek at theeks dot net
15 years ago
It would be useful to know the precedence (for lack of a better word) for type juggling.  This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out).  Thanks!
up
0
alexgr at gmail dot com
15 years ago
For a Cast to a User Defined Object you can define a cast method:

class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
}

In your php page code you can:
$myObject = MyObject::cast($_SESSION["myObject"]);

Then, PHP will validate the value and your IDE will help you.
up
0
toma at smartsemantics dot com
19 years ago
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
    if(class_exists($class_type,true)){
        $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
          "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
    }
}
up
0
philip_snyder at hotmail dot com
20 years ago
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    // Example serialized object segment
    // O:5:"field":9:{s:5:...   <--- Class: Field
    $old_serialized_prefix  = "O:".strlen(get_class($old_object));
    $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
    $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
up
-1
Eric Lavoie
9 years ago
(array) null
array(null)

are not the same.

var_dump((array) null) =>
array (size=0)
  empty

var_dump(array (null)) =>
array (size=1)
  0 => null
up
-1
berniev
8 years ago
May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = 'abc';          // string 'abc'
$u=(array) $t;   // array 0 => string 'abc'  <-- now an array
$v=(array) $u;  // array 0 => string 'abc'  <-- unchanged
up
-2
mbrowne83 (at GM)
9 years ago
The code listed in some of the comments here for supposedly "casting" from one class to another using unserialize/serialize does not actually change the class of the existing object; it creates a new object. So it's not the same as a cast.
up
-4
tom5025_ at hotmail dot com
19 years ago
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
up
-4
post_at_henribeige_dot_de
20 years ago
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
    return unserialize($new_serialized_object);
  }
  else
    return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
up
-4
dimo dot vanchev at bianor dot com
20 years ago
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
    if(
class_exists($new_classname)) {
       
$old_serialized_object = serialize($old_object);
       
$old_object_name_length = strlen(get_class($old_object));
       
$subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
       
$new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
       
$new_serialized_object .= substr($old_serialized_object, $subtring_offset);
        return
unserialize($new_serialized_object);
     } else {
         return
false;
     }
}
?>
up
-6
nullhilty at gmail dot com
15 years ago
Just a little experiment on the (unset) type cast:

<?php
$var
= 1;
$var_unset = (unset) $var;
$var_ref_unset &= (unset) $var;
var_dump($var);
var_dump($var_unset);
var_dump($var_ref_unset);
?>

output:
int(1)
NULL
int(0)
up
-6
davaakhuu at outlook dot com
8 years ago
Type Juggling<br/>
   <?php $count = "2 cats"; ?>
   Type: <?php echo gettype($count); ?><br/>
   <?php $count += 3; ?>
   Type: <?php echo gettype($count); ?><br/>
   <?php $cats = "I have " . $count . "cats."; ?>
   Cats: <?php echo gettype($cats); ?><br/>
   <br/>
   Type Casting<br/>
   <?php settype($count, "integer"); ?>
   count: <?php echo gettype($count); ?><br/>

   <?php $count2 = (string)$count; ?>
   count: <?php echo gettype($count); ?><br/>
   count2: <?php echo gettype($count2); ?><br/>

   <?php $test1 = 3; ?>
   <?php $test2 = 3; ?>
   <?php settype($test1, "string"); ?>
   <?php (string)$test2; ?>
   test1: <?php echo gettype($test1); ?><br/>
   test2: <?php echo gettype($test2); ?><br/>
up
-8
kajsunansis at that gmail
15 years ago
json_decode users consider this, when casting stdClass to array:
<?php
$obj
= new stdClass();
$obj->{"2"} = "id";
$arr = (array) $obj;
$result = isset($arr["2"]) || array_key_exists(2, $arr); // false
?>
..though casting is at least 2x faster than foreach.
up
-17
Jeffrey
15 years ago
IMAGINATION REQUIRED...

We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.
+-------+------+------+-------+
| index | $var | type | value |
+-------+------+------+-------+
|     1 |  --- | NULL |  null |
|     2 |  --- | NULL |  null |
|     3 |  --- | NULL |  null |
|     4 |  --- | NULL |  null |
+-------+------+------+-------+

<?php
# create some variables...
$a = 10;
$b = "Hello";
$c = array(55.45, 98.65);
# Now look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a | INTEGER |     10 |
|     2 |    $b |  STRING |  Hello |
|     3 | $c[0] |   FLOAT |  55.45 |
|     4 | $c[1] |   FLOAT |  98.65 |
+-------+-------+---------+--------+
<?php
# Now, change the variable types...
$a = "Bye";
$b = 2;
$c[0] = "Buy";
$c[1] = "Now!";
#Look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a |  STRING |    Bye | <- used to be INTEGER
|     2 |    $b | INTEGER |      2 | <- used to be STRING
|     3 | $c[0] |  STRING |    Buy | <- used to be FLOAT
|     4 | $c[1] |  STRING |  Right | <- used to be FLOAT
+-------+-------+---------+--------+
To Top