php - 类属性总是设置为字符串?
问题描述
今天我第一次注意到这一点,同时使用 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 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
你得到相同的结果还是有什么你没有告诉我们我在这里遗漏的东西。
推荐阅读
- java - java - 如何保持while循环直到电话响起java
- db2 - 在 Cygwin 中使用 DB2 时的 SQL1024N
- html - 表格未显示 ngFor-Angular 11 的所有行
- function - Python:在while循环中调用函数时每次迭代的函数调用堆栈
- android - 无法通过传递其 Uri / UID 有意访问文件?
- java - 我遇到了 java.lang.IllegalStateException 错误的问题
- javascript - 如何在reactjs中检测事件关闭窗口浏览器(不是TAB)?
- influxdb - 自月初以来按月汇总,使用 Flux 语言时区偏移
- spring-boot - 发生异常时强制 Spring Boot 应用程序退出
- flutter - Flutter:单元测试一个 Cubit 问题