简体   繁体   English

从PHP中的对象获取属性

[英]Get property from an object in PHP

Have to do some php coding but I am totally new to it. 必须做一些php编码,但我是完全陌生的。 The question is I was trying to get a property value from an object called $mgm_member, this object is from wordpress plugin which records website's member info. 问题是我试图从名为$ mgm_member的对象获取属性值,该对象来自wordpress插件,该插件记录网站的会员信息。 First I use: 首先,我使用:

var_dump(get_object_vars($mgm_member)); 

The results shows that this obeject has 37 properties and all of them have values. 结果表明,该对象具有37个属性,并且全部具有值。 Than I tried use 比我尝试使用

var_dump($mgm_member->phone);

The result is null. 结果为空。 I tried many other properties but only the first property of this object have value. 我尝试了许多其他属性,但是只有该对象的第一个属性才有价值。 Can anyone help me? 谁能帮我? Thank you very much. 非常感谢你。

well I suppose if the scope of "phone" is private var_dump will not be able to access and view it, is it? 好吧,我想如果“电话”的范围是私有的var_dump将无法访问和查看它,是吗? In my case, I can view all properties and their values using var_dump() function but when I tried to get one property it just doesn't work. 就我而言,我可以使用var_dump()函数查看所有属性及其值,但是当我尝试获取一个属性时,它就无法正常工作。 However,I can get the first property "id" using the same code 但是,我可以使用相同的代码获得第一个属性“ id”

echo $mgm_member->id;

That is really weird. 真是奇怪

var_dump(get_object_vars($mgm_member)); shows the object variables. 显示对象变量。 If you are getting data with this line of code, you have data in your object. 如果要通过此行代码获取数据,则对象中有数据。

You can access properties of a variable in your code with $mgm_member->phone - why not do so? 您可以使用$mgm_member->phone在代码中访问变量的属性-为什么不这样做?

If you want to place the data into a variable you can use something like this: 如果要将数据放入变量中,则可以使用以下方法:

$myVar=$mgm_member->phone;

but that defeats the purpose of OOP. 但这违反了OOP的目的。 Why not refer to it as exactly $mgm_members->phone all the way through your code? 为什么不在代码中$mgm_members->phone将其完全称为$mgm_members->phone

Edit: As you point out, the property is private which means that only the object itself can use it. 编辑:正如您所指出的,该属性是private ,这意味着只有对象本身可以使用它。 You could get around this by modifying the object, but this may be a nasty approach - it is private for a reason. 可以通过修改对象来解决此问题,但这可能是一种令人讨厌的方法-由于某种原因它是私有的。 Can you not use functions within the object to display the values? 您不能使用对象内的函数来显示值吗? Alternately, is there a function you can use in the object to return you a clone of the object with different property attributes? 或者,是否可以在对象中使用一个函数来返回具有不同属性属性的对象的克隆?

As the property is 'private' you will need to make a function to access and return it . 由于该属性是“私有”的,因此您需要创建一个函数来访问和返回它

A dump may display them but you WILL NOT be able to directly access a 'private' property. 转储可能会显示它们,但您将无法直接访问“私有”属性。

class .... {

    public function getPhone()
    {
        return ($this->phone);
    }

}

then: 然后:

echo $mgm_member->getPhone();

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

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