PHP调试以列出单个变量的数据类型更改


PHP debugging to list change of datatype of a single variable

是否有任何方法来调试PHP代码,它将列出变量在其数据类型中经历了多少次更改?

例如:

$x = 12.4;
//some code
.
.
$x = 'Sam';
//some code
.
.
$x = 'Hello world';
//some code
.
.
$x = 45;
//some code
.
.
$x = 23;
//some code
.
.
$x = true;

对应的输出是-

float
string
string
integer
integer
boolean

可以在每次出现//some code的位置加上echo gettype($x)

From php:

返回PHP变量var的类型

返回字符串的可能值有:

  • "boolean" "integer" "double"(由于历史原因"double"在float的情况下返回,而不是简单的"float")
  • "字符串"
  • "数组"
  • "对象"
  • "资源"
  • "零"
  • "未知类型"

但是您需要显式地添加这段代码。我不认为有任何办法挂钩到一个普通变量的赋值。

另一种方法是通过函数设置值,或者使用对象来存储变量。下面的代码片段使用了一个带有魔术getter和setter的对象来捕捉每个属性的设置。但是,当然,这也可能需要更改代码,而且它也相当慢,所以像这样设置每个变量不会有效。

但是对于一个小的调试会话,它可能是有用的:

<?php
class Vars {
  private $___values = array();
  public function __get($x) {
    return $this->___values[$x];
  }
  public function __set($x, $v) {
    $this->___values[$x] = $v;
    echo gettype($v);
  }  
}
$vars = new Vars();
$vars->x = 'test'; // Echoes 'string'
$vars->x = 10; // Echoes 'integer'

你可以试试下面的代码

<?php
     $array=array(); 
     function get_type_variable($var){
        global $array; //make this array global so we can access outside
        $array[]=gettype($var);
        return($array);
    }
    //and you can use like this code
    $x='testing';
    get_type_variable($x);//string
    $x=100;
    get_type_variable($x);//integer
    $x=3.14;
    get_type_variable($x);//double
    $x=true;
    get_type_variable($x);//boolean
    $x=array(1,1,1,1,1);
    get_type_variable($x);//array
    $x=NULL;
    get_type_variable($x);//NULL
    // output Array ( [0] => string [1] => integer [2] => double 
    //[3] => boolean [4] => array [5] => NULL)
    print_r($array);
?>

这样你就可以调用get_type_variable()方法为变量,当变量需要改变它的类型