为什么var_dump可以确定私有变量的值,但是在尝试访问单个属性时却不能确定 [英] Why can var_dump ascertain values of private variables, yet it can't when trying to access a single the property

查看:73
本文介绍了为什么var_dump可以确定私有变量的值,但是在尝试访问单个属性时却不能确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象被扔到会话数组中,我想运行一个foreach 在items属性上.

I have an object that is being thrown into the session array, and I want to run a foreach on the items property.

我似乎无法访问它.我看到它是私有的,但我不禁想知道为什么var_dump可以向我显示该属性包含的内容,但是由于引发致命错误而无法读取数据吗?

I can't seem to access it. I see that it's private, but I can't help but wonder why var_dump can show me what the property contains yet I can't read the data as it throws a fatal error?

如果我真的很喜欢

I suppose I could do some output buffering and evaluate var_dump as a string if I really have to like this but it seems like there should be a better method. Any ideas how I can access _items?

目标代码var_dump自var_dump($_SESSION['PHPurchaseCart']):

The object code var_dumped from var_dump($_SESSION['PHPurchaseCart']):

object(PHPurchaseCart)#191 (4) {
  ["_items:private"]=>
  array(2) {
    [0]=>
    object(PHPurchaseCartItem)#190 (6) {
      ["_productId:private"]=>
      string(2) "80"
      ["_quantity:private"]=>
      int(1)
      ["_optionInfo:private"]=>
      string(20) "Monthly Sponsorship "
      ["_priceDifference:private"]=>
      string(3) ".01"
      ["_customFieldInfo:private"]=>
      NULL
      ["_formEntryIds:private"]=>
      array(0) {
      }
    }
    [1]=>
    object(PHPurchaseCartItem)#189 (6) {
      ["_productId:private"]=>
      string(2) "75"
      ["_quantity:private"]=>
      int(1)
      ["_optionInfo:private"]=>
      string(20) "Monthly Sponsorship "
      ["_priceDifference:private"]=>
      string(3) ".02"
      ["_customFieldInfo:private"]=>
      NULL
      ["_formEntryIds:private"]=>
      array(0) {
      }
    }
  }
  ["_promotion:private"]=>
  NULL
  ["_promoStatus:private"]=>
  int(0)
  ["_shippingMethodId:private"]=>
  NULL
}

我尝试访问它的方式:

$fun = $_SESSION['PHPurchaseCart'];
var_dump($fun->_items);
exit;

以上内容引发致命错误.

The above throws a fatal error.

推荐答案

这就是私有属性的想法:您无法访问它们.您真的不应该破坏这个概念.如果您确实要访问此类属性,请在原始类定义中将mark标记为"public".

That's the idea of private properties: You can't access them. You should really not break this concept. If you really want to access such property, mark is as "public" in the original class definition.

var_dump之所以可以访问它,是因为它是一个内部函数,并且具有查看整个对象的能力".但是,您的代码没有这种功能.

The reason why var_dump can access it is because it is an internal function, and it has the "power" to view the whole object. However, your code doesn't have that power.

我不建议这样做,但是如果您确实需要访问私有财产,则可以使用

I wouldn't recommend it, but if you really need to access a private property, you can use PHP Reflection to achieve it.

这篇关于为什么var_dump可以确定私有变量的值,但是在尝试访问单个属性时却不能确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆