How to create an empty object in PHP?

3

With an array you can do this:

$arrayVazio = array();
$arrayVazio[key1][var1] = "PHP";

You can do this with an object:

(object)$objetoVazio = "";
$objetoVazio->key1->var1 = "PHP";
    
asked by anonymous 26.05.2017 / 16:44

3 answers

7

As Diego suggested, it is possible to create an object using stdClass , it would look something like:

<?php

$class = new stdClass;
$class->key1->key2 = 1;

var_dump($class);

However I should alert you that doing this will issue a warning similar to this:

  

Warning: Creating default object from empty value

It is not a "fatal error", it is only Warn , it does not affect the execution of the script directly, however several side effects can occur, handler to handle PHP errors, or some other third-party script that does some checking, type if there was an error previously and then only process if there are no errors, relative as I said are collating effects does not mean that they will occur at any time, it just means that may maybe occur.

So one way I might suggest to create an object would be to maybe use an array and make 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 stdClass :

<?php

$foo = new stdClass;

if (!isset($foo->key1)) {
     $foo->key1 = new stdClass;
}

$foo->key1->key2 = 1;

var_dump($foo);

This is very "raw" examples, but it's to understand logic, something that might be interesting would be to create something similar to XPath to arrays or stdClass , it 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 improve adapt and do as you wish.

Of course, if you have full control over your scripts and any third-party libraries you are using or frameworks and you are sure that Warnings will not cause side effects , then more than enough just use this:

$foo = new stdClass;
$foo->key1->key2->key3 = 'Olá mundo!';
    
26.05.2017 / 17:07
6

In PHP 7 you can still use anonymous classes, including defining 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 output will be:

SOpt
SOpt
Objeto criado com classe anônima
class@anonymous/home/dJc0UT/prog.php0x2b8e54b21146
  

See working at Ideone .

    
26.05.2017 / 16:57
2

Standard class. Read more at: link

$class = new stdClass();
    
26.05.2017 / 16:45