PHP 8.6.0 Beta 1 is available for testing

var_representation

(PECL var_representation >= 0.1.0)

var_representationDevuelve una representación legible, corta y analizable de una variable

Descripción

function var_representation(mixed $value, int $flags = 0): string

var_representation() (de la PECL var_representation) devuelve un string de caracteres con información estructurada sobre la variable dada. Es similar a var_export() con diferencias en la indentación, escape de strings y las representaciones de array.

Parámetros

value

La variable para generar una representación.

flags

Una máscara de bits que consiste en VAR_REPRESENTATION_SINGLE_LINE , VAR_REPRESENTATION_UNESCAPED . El comportamiento de estas constantes se describe en la página de las constantes de var_representation.

Valores devueltos

Devuelve la representación de la variable.

Ejemplos

Ejemplo #1 Ejemplo de var_representation()

<?php
$a = [1, 2, ['key' => 'value']];
echo var_representation($a), "\n";
echo var_representation($a, VAR_REPRESENTATION_SINGLE_LINE), "\n";
?>

El ejemplo anterior mostrará:

[
 1,
 2,
 [
 'key' => 'value',
 ],
]
[1, 2, ['key' => 'value']]

Ejemplo #2 Escapado de caracteres de control

<?php
echo var_representation("Content-Length: 123\r\n");
?>

El ejemplo anterior mostrará:

"Content-Length: 123\r\n"

Ejemplo #3 Exportar una stdClass

<?php
$person = new stdClass;
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';
echo var_representation($person);
?>

El ejemplo anterior mostrará:

(object) [
 'name' => 'ElePHPant ElePHPantsdotter',
 'website' => 'https://php.net/elephpant.php',
]

Ejemplo #4 Exportar clases

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
echo var_representation($a);
?>

El ejemplo anterior mostrará:

\A::__set_state([
 'var' => 5,
])

Ejemplo #5 Uso con __set_state()

<?php
class A
{
 public $var1;
 public $var2;
 public static function __set_state($an_array)
 {
 $obj = new A;
 $obj->var1 = $an_array['var1'];
 $obj->var2 = $an_array['var2'];
 return $obj;
 }
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_representation($a) . ';'); // $b = \A::__set_state([
 // 'var1' => 5,
 // 'var2' => 'foo',
 // ]);
var_dump($b);
?>

El ejemplo anterior mostrará:

object(A)#2 (2) {
 ["var1"]=>
 int(5)
 ["var2"]=>
 string(3) "foo"
}

Véase también

  • var_export() - Devuelve el código PHP utilizado para generar una variable

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes

There are no user contributed notes for this page.

AltStyle によって変換されたページ (->オリジナル) /