3
With an array you can do this:
$arrayVazio = array();
$arrayVazio[key1][var1] = "PHP";
It is possible to do this with an object:
(object)$objetoVazio = "";
$objetoVazio->key1->var1 = "PHP";
3
With an array you can do this:
$arrayVazio = array();
$arrayVazio[key1][var1] = "PHP";
It is possible to do this with an object:
(object)$objetoVazio = "";
$objetoVazio->key1->var1 = "PHP";
7
As Diego suggested it is possible to create an object using stdClass
, would look something like:
<?php
$class = new stdClass;
$class->key1->key2 = 1;
var_dump($class);
However I must warn you that by doing this you will issue a warning
similar to this:
Warning: Creating default Object from Empty value
It’s not a "fatal mistake," it’s just a Warn
, does not affect the execution of the script directly, however several side effects, even more if you have a Handler to manipulate PHP errors, or some other third party script that does some checking, like if there was an error earlier and then would only process if there are no errors, it is something relative good, as I said are side effects, does not mean that they will occur at any time, only means that may perhaps occur.
So one way I should suggest to create an object would be to maybe use an array and do the cast
(with (object)
):
<?php
$foo = (object) array(
'key1' => (object) array(
'key2' => 2
)
);
var_dump($foo);
Or you could create a check to see if the key exists, then add items to the stdClass
:
<?php
$foo = new stdClass;
if (!isset($foo->key1)) {
$foo->key1 = new stdClass;
}
$foo->key1->key2 = 1;
var_dump($foo);
These are very "raw" examples, but it’s to understand the logic, something that might be interesting would be to create something similar to a XPath
for arrays
or stdClass
, would look something like:
<?php
/*
- &$obj Passa o objeto como referencia
- $path informa o caminho desejado
- $value informa o valor desejado
*/
function setPath(&$obj, $path, $value) {
$paths = explode('.', $path); //Pega todas dimensões desejadas
$last = array_pop($paths); //Pega a ultima dimensão
$isArray = is_array($obj); //Verifica se é um array como padrão
$current = $obj; //Objecto atual da primeira dimensão
foreach ($paths as $path) {
if (!isset($current->$path)) {
$current->$path = $isArray ? array() : new \stdClass;
}
$current = $current->$path;
}
$current->$last = $value; //Define o valor na ultima dimensão
}
$foo = new stdClass;
setPath($foo, 'key1.key2.key3', 'Olá Mundo!');
var_dump($foo);
That would result in this:
object(stdClass)#1 (1) {
["key1"]=>
object(stdClass)#2 (1) {
["key2"]=>
object(stdClass)#3 (1) {
["key3"]=>
int(1)
}
}
}
This example is very simple, of course it is not perfect, its goal is to show in a simple way how to do this, you can better adapt and do as you wish.
Of course, if you have full control over your scripts and the third-party libraries you use or frameworks and you are absolutely sure that Warnings
will not cause side effects, then will be more than enough use only this:
$foo = new stdClass;
$foo->key1->key2->key3 = 'Olá mundo!';
6
In PHP 7 you can still use anonymous classes, including setting methods for such an object:
$obj = new class {
public function __construct ()
{
$this->key1 = new stdClass();
$this->key1->var1 = "SOpt";
}
public function getKey1 ()
{
return $this->key1;
}
public function __toString ()
{
return "Objeto criado com classe anônima";
}
};
// Acessando o atributo diretamente:
echo $obj->key1->var1, PHP_EOL;
// Acessando o atributo através do método get:
echo $obj->getKey1()->var1, PHP_EOL;
// Chamando o método __toString do objeto:
echo $obj, PHP_EOL;
// Exibindo a classe do objeto:
echo get_class($obj), PHP_EOL;
The exit will be:
SOpt
SOpt
Objeto criado com classe anônima
class@anonymous/home/dJc0UT/prog.php0x2b8e54b21146
See working on Ideone.
2
Standard class. Read more in: http://php.net/manual/en/reserved.classes.php
$class = new stdClass();
Browser other questions tagged php oop
You are not signed in. Login or sign up in order to post.
You have a question on stackoverflow in exactly the same English: https://stackoverflow.com/questions/1434368/how-to-define-an-empty-object-in-php
– Don't Panic
It is interesting that we create in Sopt also because not everyone has the knowledge in English. We also have to see that this answer is old and we have to make room for up-to-date answers, like Anderson’s.
– Velasco
@Everson I agree with Velasco, every question brought to Sopt that already exists in Soen is intended to bring knowledge, Sopt is not son of Soen, each community is one, speak of the same subject but has no direct connection, here the focus is a target audience, in the case native to the Portuguese language
– Guilherme Nascimento
That’s why it was put in the comments ;)
– Don't Panic
It’s just that the comment had sounded different @Everson, but I get it now ;)
– Guilherme Nascimento