Pregunta

I wrote some program to check the value in an array.

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??

Could somebody can explain how this happened?

background:

I modified the kernel of wordpress.

This happened when I modified the file of wp-admin/user-edit.php.

¿Fue útil?

Solución

You say it's an array, but you're accessing it as an object ($obj->foo rather than $arr['foo']), so it's most likely an object (actually it is - get_user_to_edit returns a WP_User). It could easily contain the magic __get and __isset methods that would lead to this behaviour:

<?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

Otros consejos

One possibility is that $profileuser is an Object that behaves as an array and not an array itself.

This is possible with interface ArrayAccess. In this case, isset() would return true and you might not see it when you do var_dump($profileuser);.

When you want an object to behave like an array, you need to implement some methods which tell your object what to do when people use it as if it were an array. In that case, you could even create an Object that, when accessed as an array, fetches some webservice and return the value. That may be why you are not seeing those values when you var_dump your variable.

I thinks it's not possible, I've created test code and var_dump behaves correctly. Are you 100% sure you don't have any typo in your code? I remind variables in PHP are case sensitive

<?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??

Result is:

null

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

vcv
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top