var_dump不显示PHP数组值,但它已被提取。

时间:2014-05-03 15:01:37

标签: php wordpress var-dump

我写了一些程序来检查数组中的值。

var_dump($profileuser);//NULL

$profileuser = get_user_to_edit($user_id);//fetch the value of $profileuser

var_dump($profileuser);//does not print the value of $profileuser->user_url 
//nor by print_r($profileuser)

if(isset($profileuser->user_url))
    echo $profileuser->user_url;//printed!!!!How is it possible??

有人可以解释这是怎么发生的吗?

背景:

我修改了wordpress的内核。

当我修改了wp-admin / user-edit.php。

的文件时,就发生了这种情况

3 个答案:

答案 0 :(得分:2)

您说它是一个数组,但您将其作为对象($obj->foo而不是$arr['foo'])进行访问,因此它很可能是一个对象(实际上它是 - get_user_to_edit returns a WP_User)。它可以很容易地包含导致此行为的神奇的__get__isset方法:

<?php

class User {
    public $id = 'foo';

    public function __get($var) {
        if ($var === 'user_url') {
            return 'I am right here!';
        }
    }

    public function __isset($var) {
        if ($var === 'user_url') {
            return true;
        }

        return false;
    }
}

$user = new User();

print_r($user);
/*
    User Object
    (
        [id] => foo
    )
*/

var_dump( isset($user->user_url) ); // bool(true)
var_dump( $user->user_url ); // string(16) "I am right here!"

DEMO

答案 1 :(得分:1)

一种可能性是$profileuser是一个行为数组而不是数组本身的对象。

接口ArrayAccess可以实现这一点。在这种情况下,isset()将返回true,当您执行var_dump($profileuser);时可能看不到它。

当您希望对象的行为类似于数组时,您需要实现一些方法,这些方法告诉您的对象当人们使用它时如何操作,就好像它是一个数组一样。在这种情况下,您甚至可以创建一个Object,当作为数组访问时,它会获取一些Web服务并返回该值。这可能是您var_dump变量时没有看到这些值的原因。

答案 2 :(得分:0)

我认为这是不可能的,我已经创建了测试代码并且var_dump行为正确。您是否100%确定您的代码中没有任何拼写错误?我提醒PHP中的变量是区分大小写的

<?php


$profileuser = null;


class User
{
  public $user_url;

}
function get_user_to_edit($id) {
$x = new User();  
  $x->user_url = 'vcv';
  return $x;

}

var_dump($profileuser);//NULL
$user_id = 10;
$profileuser = get_user_to_edit($user_id);//fetch the value of $profileuser

var_dump($profileuser);//does not print the value of $profileuser->user_url 
//nor by print_r($profileuser)

if(isset($profileuser->user_url))
  echo $profileuser->user_url;//printed!!!!How does it possible??

结果是:

null

object(User)[1]
  public 'user_url' => string 'vcv' (length=3)

vcv