简体   繁体   English

访问通过解码JSON字符串创建的对象属性时的空值

[英]Null value when accessing object property created by decoding JSON string

In my PHP script I need to decode a Json string and then transfer the decoded value to a class. 在我的PHP脚本中,我需要解码Json字符串,然后将解码后的值传输到类。 Something like: 就像是:

index.php index.php

$params = json_decode('input');
$obj = new User();
$obj->setParams($params);
$obj->Register();

class.php class.php

class User{
private $mParams;

public function setParams($params)
    $mParams = $params;
}

public function Register(){
    $username = $mParams->{'username'};
    $password = $mParams->{'password'};
}
....
}

The problem is, in Register(), when I print the $username and $password, I just got NULL. 问题是在Register()中,当我打印$ username和$ password时,我只是得到了NULL。 But I'm sure the $params decoded from Json is not NULL because, if I print it in setParams, I can get username and password. 但是我确定从Json解码的$ params不是NULL,因为如果我在setParams中打印它,我可以获得用户名和密码。 And, if I directly transfer the $params to Register() everything is fine. 而且,如果我直接将$ params传输到Register(),一切都很好。

So I feel strange that why I can not set the $params to the class's member and then call the class's member function to access it. 所以我感到奇怪的是,为什么我不能将$ params设置为该类的成员,然后再调用该类的成员函数来访问它。

Thanks, 谢谢,

$this->mParams->username
 ^^^^^^

You want to access the object's property, so use $this . 您要访问该对象的属性,因此请使用$this Also, no need for the string-in-brackets syntax. 而且,不需要括号中的字符串语法。

When setting the member variables of an object in php, you must prefix $this-> to distinguish them from local variables. 在php中设置对象的成员变量时,必须在$this->加上前缀以将它们与局部变量区分开。 You want: 你要:

class User{
  private $mParams;

  public function setParams($params)
      $this->mParams = $params;
  }

  public function Register(){
      $username = $this->mParams->{'username'};
      $password = $this->mParams->{'password'};
      echo $username . " : " . $password;
  }
  ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM