¿Puede explicarnos el siguiente comportamiento interesante?Matriz de Objeto y Objeto para Matriz en PHP - comportamiento interesante
class test {
//Class *test* has two properties, public and private.
public $xpublic = 'x1';
private $xprivate = 'x2';
}
$testObj = new test();
Vamos a convertir $testObj
en una matriz.
settype($testObj, 'array');
var_dump($testObj);
Resultado:
array(2) { ["xpublic"]=> string(3) "x1" ["testxprivate"]=> string(4) "x2" }
OK, xprivate
propiedad se convierte en testxprivate
Convirtamos esta matriz de oponerse.
$newObj = (object)$testObj;
var_dump($newObj);
Resultado:
object(stdClass)#1 (2) { ["xpublic"]=> string(3) "xxx" ["xprivate":"test":private]=> string(4) "xxx3" }
$newObj
es un objeto stdClass
.
Y la pregunta es:
¿Por qué testxprivate
se convierten en una propiedad privada xprivate
(no testxprivate
) del nuevo objeto? ¿Cómo sabe PHP que la matriz $testObj
era un objeto?
Si defino la igualdad de matriz:
$testArray = array('xpublic'=>'x1', 'testxprivate'=>'x2');
y luego convertirlo en objeto:
var_dump((object)$testArray);
Voy a por el objeto con dos propiedades públicas y xpublic
testxprivate
como se esperaba:
object(stdClass)#2 (2) { ["xpublic"]=> string(2) "x1" ["testxprivate"]=> string(2) "x2" }