简体   繁体   English

如何在PHP中打印类的项目?

[英]How can I print the items of a class in PHP?

I have this class: 我有这个课:

class MyClass {
    public $dummy = array('foo', 'bar', 'baz', 'qux');
    public $progr = array('HTML', 'CSS', 'JS', 'PHP');
}

I'm trying to print that out: print_r(MyClass) , but it outputs MyClass and nothing else. 我正在尝试将其打印出来: print_r(MyClass) ,但是它输出MyClass,而没有其他输出。 I get similiar things with echo , print , var_dump and var_export . 我得到类似的东西与echoprintvar_dumpvar_export It seems that they treat MyClass as a string, because echo(test) outputs test . 似乎他们将MyClass视为字符串,因为echo(test)输出test

So, how can I list the items of a class? 那么,如何列出课程的项目?

Use ReflectionClass on an instance of your class, and optionally use ReflectionProperty to get the values of the properties as in your instance: 使用ReflectionClass你的类的实例,并有选择地使用ReflectionProperty获取属性的值作为您的实例:

$rc = new ReflectionClass(new MyClass());

foreach ($rc->getProperties() as $property) {
    printf('%s = %s', $property->getName(), print_r($property->getValue(), true));
}

On second thought, if you just want to get the values of an object's properties then mingos' answer using print_r(new MyClass()); 再次考虑,如果您只想获取对象属性的值,则使用print_r(new MyClass()); mingos的答案print_r(new MyClass()); works too. 也可以。

Another thing, 另一件事,

It seems that they treat MyClass as a string, because echo(test) outputs test . 似乎他们将MyClass视为字符串,因为echo(test)输出test

This is normal: PHP first treats them as constant names, but if it can't find constants defined with those names, then it treats them as unquoted string literals. 这是正常的:PHP首先将它们视为常量名称,但是如果找不到用这些名称定义的常量,则将它们视为未加引号的字符串文字。

Have you instantiated it? 您实例化了吗?

What does this output: 这输出什么:

$m = new MyClass();
print_r($m);

Sometimes it can be helpful to implement the class's __toString magic method as well. 有时也可以实现类的__toString magic方法。 In brief, __toString allows you to specify exactly how an object should behave when it is echoed. 简而言之,__toString允许您确切指定对象在回显时的行为。 For more information, please see the following: 有关更多信息,请参见以下内容:

http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring http://www.php.net/manual/zh-CN/language.oop5.magic.php#language.oop5.magic.tostring

I like to use __toString as a debugging tool, though I'm sure the true potential of the method is significantly more profound :) 我喜欢将__toString用作调试工具,尽管我确信该方法的真正潜力会更加深远:)

Hope that helps. 希望能有所帮助。

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

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