php как распечатать объект
(PHP 4, PHP 5, PHP 7, PHP 8)
print — Выводит строку
Описание
Список параметров
Возвращаемые значения
Примеры
Пример #1 Примеры использования print
print «print не требует скобок.» ;
// Новая строка или пробел не добавляются; ниже выводит «приветмир» в одну строку
print «привет» ;
print «мир» ;
print «Эта строка занимает
несколько строк. Новые строки
также будут выведены» ;
print «Эта строка занимает\nнесколько строк. Новые строки\nтакже будут выведены» ;
// Нестроковые выражения приводятся к строковым, даже если используется declare(strict_types=1)
print 6 * 7 ; // 42
// Поскольку print имеет возвращаемое значение, его можно использовать в выражениях
// Следующие выходные данные «привет мир»
if ( print «привет» ) <
echo » мир» ;
>
Примечания
Замечание: Использование с круглыми скобками
print «привет» ;
// выведет «привет»
print( 1 + 2 ) * 3 ;
// выведет «9»; круглые скобки приводят к тому, что сначала вычисляется 1+2, а затем 3*3
// оператор print видит все выражение как один аргумент
При использовании print в более крупном выражении может потребоваться размещение ключевого слова и его аргумента в круглых скобках для получения желаемого результата:
print «привет » && print «мир» ;
// выведет «мир1»; print «мир» выполняется в первую очередь,
// тогда выражение «привет» && 1 передается в левую часть print
(print «привет » ) && (print «мир» );
// выведет «привет мир»; круглые скобки заставляют выражения print
// выполнятьтся перед &&
?>
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Смотрите также
User Contributed Notes 9 notes
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.
Most would expect the following behavior:
if (print( «foo» ) && print( «bar» )) <
// «foo» and «bar» had been printed
>
?>
But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is
and the argument of the second print is just
For the expected behavior of the first example, you need to write:
if ((print «foo» ) && (print «bar» )) <
// «foo» and «bar» had been printed
>
?>
Running in a browser:
Running in a shell:
the FAQTs article can be found archived at http://web.archive.org/web/20060601063513/http
://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
(url split to get past the line-length limitation)
mvpetrovich of 2007 could just use single quotes as his string delimiters (see the example in the current documentation).
It’s not ALWAYS appropriate, but generally it is best (the Zend Framework coding standards have a good take on this). It yields a number of interesting benefits:
1: Nobody will be tempted to write functions to replace backticks or other characters with double quotes. Such functions may cause a (negligible) loss of efficiency, and maybe other undesired effects.
2: You will be able to use double quotes without escaping. This is recommended (although not required) for HTML and XML attributes, as well as quoted text.
3: The script will hit the browser very slightly slightly faster since PHP doesn’t have to scan through the string looking for variables, escaped characters, curly braces or other things.
4: Your code gets ten times easier to read. (as mvpetrovich pointed out)
If, in spite of these four excellent benefits, you really MUST still use double quotes to delimit boring old string constants (and seriously, why would you?), you could use the slightly less favourable single quotes as delimiters for most markup languages.
HTML served as HTML will even let you lay out unquoted attributes (yuck).
It should also be noted though that if you are just printing bare strings, you may as well shut off the php parser. The quickest way to send a string is to write it as plain text, OUTSIDE of the php tags. This will also make your code look excellent in a lot of syntax highlighters.
There are few disadvantages to doing this, if any. Output buffering still works. All your classes and objects and includes remain in place. Your script runs faster. World peace is obtained.
I have a small utility run from the command line that processes a potentially huge list of files. As it can take hours to complete, I stuck a
statement in the body of the main loop to prove that something was happening.
For reasons unknown to me, the utiliity suddenly started buffering the output such that it printed nothing until completion, defeating the purpose of the running monitor. Adding flush() statements did nothing. The problem was solved by using
but I have no idea why.
Don’t rely on parenthesis used for `print` construct:
I have written a script to benchmark the several methods of outputting data in PHP: via single quotes, double quotes, heredoc, and printf. The script constructs a paragraph of text with each method. It performs this construction 10,000 times, then records how long it took. In total, it prints 160,000 times and records 16 timings. Here are the raw results.
Outputted straight to browser—
Single quotes: 2,813 ms
. with concatenation: 1,179 ms
Double quotes: 5,180 ms
. with concatenation: 3,937 ms
heredoc: 7,300 ms
. with concatenation: 6,288 ms
printf: 9,527 ms
. with concatenation: 8,564 ms
Outputted to the output buffer—
Single quotes: 8 ms
. with concatenation: 38 ms
Double quotes: 8 ms
. with concatenation: 47 ms
heredoc: 17 ms
. with concatenation: 49 ms
printf: 54 ms
. with concatenation: 52 ms
A nice graph of the script’s output can be found here:
http://i3x171um.com/output_benchmarks/ob.gif
So what should you choose to print your text? I found several things out writing this.
First, it should be noted that the print and echo keywords are interchangeable, performance-wise. The timings show that one is probably an alias for the other. So use whichever you feel most comfortable with.
Second, if you’ve ever wondered which was better, the definitive answer is single quotes. Single quotes are at least four times faster in any situation. Double quotes, while more convenient, do pose a debatably significant performance issue when outputting massive amounts of data.
Third, stay away from heredoc, and absolutely stay away from [s]printf. They’re slow, and the alternatives are there.
DO NOT RUN THE SCRIPT ON THE INTERNET! Run it instead from localhost. The script outputs
45 megabytes of text in an html comment at the top of the page by default. Expect the benchmark to take
45 seconds. If this is too long, you can change the amount of iterations to a lower number (the results scale accurately down to about 1,000 iterations).
PHP-печать всех свойств объекта
У меня есть неизвестный объект на странице php.
Как я могу распечатать / Эхо, чтобы я мог видеть, какие свойства / значения у него есть?
насчет функций? Есть ли способ узнать, какие функции имеет объект?
7 ответов
Это то же самое, что вы используете для массивов.
Они будут показывать защищенные и частные свойства объектов с PHP 5. Статические члены класса не будут отображаться в соответствии с руководством.
Если вы хотите знать методы членов, которые вы можете использовать get_class_methods ():
как никто не предоставил подход ОО еще здесь, как это было бы сделано.
преимущество при использовании отражения заключается в том, что вы можете фильтровать по видимости собственность, как это:
С Person::$property является частным он возвращается при фильтрации по IS_PRIVATE:
Если вы хотите больше информации, вы можете использовать ReflectionClass:
Мне очень нравится dBug. Я обычно использую var_dump() для скаляров (int, string, boolean и т. д.) и dBug для массивов и объектов.
скриншот объекта с официального сайта:
чтобы получить больше информации, используйте эту пользовательскую функцию ($someObject):
Я написал эту простую функцию, которая не только отображает методы данного объекта, но и показывает его свойства, инкапсуляцию и некоторую другую полезную информацию, такую как заметки о выпуске, если они даны.
чтобы показать вам, как это работает, я создам теперь некоторый случайный пример класса. Позволяет создать класс под названием Person и разместить некоторые заметки о выпуске чуть выше класса объявление:
теперь давайте создадим экземпляр человека и обернем его нашей функцией.
это выведет информацию об имени класса, параметрах и методах, включая информацию инкапсуляции и количество параметров, имена параметров для каждого метода, местоположение метода и строки кода, где он существует. См. вывод ниже:
надеюсь, вы найдете его полезным. С уважением.
попробуйте использовать Довольно Свалку на
для знания свойств объекта var_dump (object) является лучшим способом. Он покажет все государственные, частные и защищенные свойства, связанные с ним, не зная имени класса.
но в случае методов вам нужно знать имя класса, иначе я думаю, что трудно получить все связанные методы объекта.
How to print all properties of an object
I have an unknown object in php page.
How can I print/echo it, so I can see what properties/values do it have?
What about functions? Is there any way to know what functions an object have?
7 Answers 7
These are the same things you use for arrays too.
These will show protected and private properties of objects with PHP 5. Static class members will not be shown according to the manual.
If you want to know the member methods you can use get_class_methods():
As no one has not provided an OO approach yet here is like it would be done.
The advantage when using reflection is that you can filter by visibility of property, like this:
Since Person::$property is private it’s returned when filtering by IS_PRIVATE:
If you want more info you can use a ReflectionClass:
To get more information use this custom TO($someObject) function:
I wrote this simple function which not only displays the methods of a given object, but also shows its properties, encapsulation and some other useful information like release notes if given.
To show you how it works I will create now some random example class. Lets create class called Person and lets place some release notes just above the class declaration:
Now lets create a instance of a Person and wrap it with our function.
This will output information about the class name, parameters and methods including encapsulation information and the number of parameters, names of parameters for each method, method location and lines of code where it exists. See the output below:
print_r
(PHP 4, PHP 5, PHP 7, PHP 8)
print_r — Выводит удобочитаемую информацию о переменной
Описание
print_r() выводит информацию о переменной в удобочитаемом виде.
Список параметров
Выражение для вывода на экран.
Возвращаемые значения
Примеры
Пример #1 Пример использования print_r()
Результат выполнения данного примера:
Пример #2 Пример использования параметра return
Примечания
Смотрите также
User Contributed Notes 36 notes
I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.
Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.
I always use this function in my code, because most of my functions return an Array or Boolean :
?>
( print_r gives no output on FALSE and that can be annoying! )
This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky. ):
The following will output an array in a PHP parsable format:
Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)
// replace ‘)’ on its own on a new line (surrounded by whitespace is ok) with ‘
A simple function to send the output of print_r to firebug.
The script creates a dummy console object with a log method for when firebug is disabled/not available.
This is an alternative for printing arrays. It bolds array values.
I was having problems using print_r because I didn’t like the fact that if tags where included in the array it would still be parsed by the browsers.
Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser’s «view source» or CLI.
A slight modification to the previous post to allow for arrays containing mutli line strings. haven’t fully tested it with everything, but seems to work great for the stuff i’ve done so far.
$output = ‘
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
[3] => Array
(
[nest] => yes
[nest2] => Array
(
[nest] => some more
asffjaskkd
)
[nest3] => o rly?
)
)
)
?>
This should output
print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!
Here is a print_r() clone but support max level limit.
When we want to print a big object, this will help us get a clean dumping data.
$test = new testClass ;
testClass Object
(
[a:protected] => aaa
[b:testClass:private] => bbb
[c] => Array
(
[0] => 1
[1] => 2
[2] => Array
*MAX LEVEL*
[d:static] => ddd
[e:protected:static] => eee
[testClass] =>
*RECURSION*
You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:
I use this all the time when debugging objects, but when you have a very large object with big arrays of sub-objects, it’s easy to get overwhelmed with the large amount of output. sometimes you don’t want to see absolutely every sub-object.
I made this function to debug objects while «hiding» sub-objects of certain types. This also color codes the output for a more readable printout.
If you have to catch the output without showing it at all at first (for example, if you want to append the print_r output to a file), you can do this:
Another slight modification to the previous post to allow for empty array elements
my take on the highlighted markupped debug function:
/**
* print_array()
* Does a var_export of the array and returns it between » );
>
?>
For those of you needing to print an array within a buffer callback function, I’ve created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It’s recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!
Here’s a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:
test Object (
[var1] => a
[var2:protected] => b
[var3:private] => c
[array:protected] => Array (
[0] => x
[1] => y
[2] => z
)
[recursiveRef] => *RECURSION*
[anotherRecursiveRef] => stdClass Object (
[recursiveRef] => *RECURSION*
)
)
Another attempt that tries to overcome the memory blowout when the passed in data has mutual recursion.
I include the entire function below for completeness, but all credit to Matt, the original author, Thank You.
We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r’s 2nd argument
wasn’t helpful. Here is how we solved the problem:
Функция print_r()
Функция print_r – выводит удобочитаемую информацию о переменной, используется при отладке программ.
Давайте рассмотрим пример, как работает эта функция:
В этом простом примере функция print_r просто вернула значение переменной. Пользы от функции print_r в данном случае мало, но её используют обычно для просмотра массивов.
В следующем примере мы используем функцию print_r для просмотра массива:
В данном случа мы передали в функцию массив, в который вложили другой массив. Полученный результат читать не очень удобно, так как браузер не показывает переносы строк. Чтобы увидеть обещенный удобочитаемый результат, нужно просмотреть html-код страницы, или добавить тег pre перед функцией.
В следующем примере мы только добавим тег pre к предыдущему, чтобы увидеть отличия:
Теперь результат действительно удобочитаемый.
Перехват вывода print_r
Давайте рассмотрим пример перехвата вывода функции print_r() :
Результат работы этого кода полностью аналогичен предыдущему примеру.
Функции print_r и var_dump
Функция print_r() выводит удобочитаемую, но не полную информацию о переменной. Например попробуем вывести несуществующую переменную:
Функция print_r() тут ничего не вывела.
При отладке программ, а функции print_r() и var_dump() используются при отладке, иногда важно знать типы переменных, а иногда хочется увидеть красиво представленный массив без лишней информации. В зависимости от этого и пользуются той или иной функцией.