【问题标题】:PHP array value isn't shown by var_dump but it was fetched.var_dump 未显示 PHP 数组值,但它已被获取。
【发布时间】:2014-06-20 04:41:54
【问题描述】:

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

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 的文件时。

【问题讨论】:

  • 听起来不太合理,你确定名字没有错别字吗?
  • var_dump($profileuser); 之后添加对exit; 的呼叫并告诉我们您看到了什么。
  • @FelipeAlmeida 我已经完成了你要我做的事情。字太多,我不能全部打印出来。但是,里面没有 $profileuser->user_url 。只显示 $profileuser->data-user_url 的值;但此值与 $profileuser->user_url 不同。
  • @Hanky웃Panky 请原谅我不知道拼写错误是什么意思。能具体解释一下吗?
  • @Ray typo on Wikipedia。错别字是几个印刷错误(拼写错误)。

标签: php wordpress var-dump


【解决方案1】:

你说它是一个数组,但你将它作为一个对象访问($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

【讨论】:

  • 这就是正在发生的事情。 get_user_to_edit 返回一个 WP_User 对象,而 object 确实有 magic methods
  • 非常感谢。我终于弄明白了!!
【解决方案2】:

一种可能性是$profileuser 是一个对象,它表现为一个数组而不是数组本身。

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

当你想让一个对象表现得像一个数组时,你需要实现一些方法来告诉你的对象当人们像使用数组一样使用它时要做什么。在这种情况下,您甚至可以创建一个对象,当作为数组访问时,它会获取一些 Web 服务并返回值。这可能是您在 var_dump 变量时看不到这些值的原因。

【讨论】:

  • 谢谢,但@h2ooooooo 给我程序作为例子。所以,我给了他最好的答案。也谢谢你!!
【解决方案3】:

我认为这是不可能的,我已经创建了测试代码并且 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

【讨论】:

  • 我用的是wordpress 3.9版,代码是在wp-admin/user-edit.php文件的第185行添加的。调用var_dump后,显示了近30个变量,但没有$profileuser ->user_url.
猜你喜欢
  • 2014-05-13
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2017-03-23
  • 2012-04-24
  • 2019-07-12
相关资源
最近更新 更多