【问题标题】:Class attributes always set as strings?类属性总是设置为字符串?
【发布时间】:2020-10-28 20:04:56
【问题描述】:

今天我第一次注意到这一点,同时使用 PHP 类静态属性 $limit 作为原始准备语句的查询限制参数,如

/**
 * @var int
 */
private static $limit = 100;

// ....

        $query = <<<EOT
SELECT id FROM table t WHERE t.id > 0 LIMIT ? EOT;

$recs = \DB::select($query, [self::$limit]);

所以上面的查询抛出了一个错误,在我看来,这个错误是因为查询生成器将它当作一个字符串。如果我将 select 语句更改为如下所示,它将按预期运行

$mcdrs = \DB::select($query, [(int)self::$limit]);

所以,虽然这本身不是问题,但我只是好奇 PHP 中的类属性总是设置为字符串是否是一个已知事实。

我什至把属性声明改成了

private static $limit = 99+1;

结果相同。只是为了确认,我执行了以下“测试”,我可以确认无论我对静态 var 声明做什么,它们都被报告为字符串。不过没试过浮点数。

    if (is_string(self::$limit)) {
        die('string');
    } elseif (is_int(self::$limit)) {
        die('int');
    } else {
        die('something else...');
    }

我可以确认变量是字符串类型的。

【问题讨论】:

    标签: php string class static attributes


    【解决方案1】:

    我想出了这个作为测试,无法复制您的发现。 这是使用 PHP 7.3.19

    /Class_test.php

    class Class_test {
        private static $limit = 100;
        private static $string = '100';
    
        public function index() {
    
            $this->check_my_type(self::$limit);
            $this->check_my_type(self::$string);
        }
    
        protected function check_my_type($value){
            if (is_string($value)) {
                echo('I am a string :'. $value);
                echo '<br>';
            }
    
            if (is_int($value)) {
                echo('I am an Integer :'.$value);
                echo '<br>';
            }
        }
    }
    

    /index.php

    <?php
    // Enable FULL Error Reporting on the screen
    // ONLY USE IN DEVELOPMENT
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    include_once('./Class_test.php');
    
    $test = new Class_test();
    $test->index();
    

    输出为:

    I am an Integer :100
    I am a string :100
    

    你得到相同的结果还是有什么你没有告诉我们我在这里遗漏的东西。

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多