【问题标题】:Is it possible in php to turn string var into type name?在 php 中是否可以将字符串 var 转换为类型名称?
【发布时间】:2013-12-11 23:55:19
【问题描述】:

那么,我可以让这段代码工作吗:

    $typename='integer';
    $tmp='12321321312';
    $var=($typename)$tmp;

WITHOUT 使用条件,例如:

    if($typename=='integer')
        $var=(integer) $tmp;

AND WITHOUT 使用 eval,例如:

   eval( '$var=(' . $typename . ') $tmp;' );

【问题讨论】:

    标签: php string types


    【解决方案1】:

    您可以使用settype。

    $typename = 'integer';
    $tmp = '12321321312'; // $tmp will be passed as a reference
    settype($tmp, $typename);
    
    // $tmp is now an integer
    

    类型的可能值是:

    • “boolean”(或者,自 PHP 4.2.0 起,“bool”)
    • “整数”(或者,自 PHP 4.2.0 起,“整数”)
    • “float”(仅在 PHP 4.2.0 之后才有可能,旧版本使用已弃用的变体“double”)
    • “字符串”
    • “数组”
    • “对象”
    • “null”(PHP 4.2.0 起)

    【讨论】:

    • 谢谢。它完美地工作。遗憾的是,我无法通过正确的搜索查询来找到此功能。
    • 太好了!不客气。我会搜索“动态类型转换”之类的东西。
    【解决方案2】:

    是的,可以使用anonymous functions(适用于 PHP 版本 => 5.3.0)。

    $typename = 'intval';
    $tmp = '2323';
    $var = $typename($tmp); // <= note the syntax difference
    var_dump($var);
    

    输出:

    int(2323)
    

    【讨论】:

    • 很好的解决方案,但是(恕我直言) settype() 更方便,因为函数的名称说明了它的作用。清除代码 == 好代码。
    猜你喜欢
    • 2019-10-13
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2018-05-24
    • 2011-12-29
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多