Question

I'm creating a simple array wrapper class and want it's __toString() method to be formatted like a Python list, eg: ["foo", "bar", 6, 21.00002351]. Converting each element to a string is not enough, since string-objects are actually enquoted in the list-representation.

Is there a repr() equivalent in PHP, and if not, what would a PHP implementation look like?

Était-ce utile?

La solution

Python's repr() returns an output where

eval(repr(object)) == object

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

So the closest thing in PHP would be

The keyword here is parseable. While functions print_r and var_dump will give a certain representation of the data passed to them, they are not easily parseable, nor do they look like PHP expression, which could be eval'd.

Example:

var_export(['foo', 'bar', 1,2,3]);

will give

array (
  0 => 'foo',
  1 => 'bar',
  2 => 1,
  3 => 2,
  4 => 3,
)

and that is perfectly valid PHP code:

$data = ['foo', 'bar', 1, 2, 3];
$repr = var_export($data, true);

// have to use it with return though to eval it back into a var
$evald = eval("return $repr;");

var_dump($evald == $data); // true

Another option would be to use serialize to get a canonical and parseable representation of a data type, e.g.

$data = ['foo', 'bar', 1, 2, 3];
$repr = serialize($data); 
// -> a:5:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;i:1;i:3;i:2;i:4;i:3;}
var_dump( unserialize($repr) == $data ); // true

Unlike var_export, the resulting representation is not a PHP expression, but a compacted string indicating the type and it's properties/values (a serialization).

But you are likely just looking for json_encode as pointed out elsewhere.

Making this a Community Wiki because I've already answered this in the given dupe.

Autres conseils

I don't know Python but PHP arrays can contain any data type and nesting levels. I don't know how that translates into your format.

There're many functions to print an array:

  • print_r()
  • var_dump()
  • var_export()

... but your format reminds me of JSON so you can simply do this:

<?php

$foo = array (
  'foo',
  'bar',
  6,
  21.00002351,
);
echo json_encode($foo); // ["foo","bar",6,21.00002351]

Of course, it's by no means automatic, i.e., this won't trigger any toString() method at all:

echo $foo; // "Array" + PHP Notice:  Array to string conversion
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top