How to define an empty object in PHP

PhpObject

Php Problem Overview


with a new array I do this:

$aVal = array();

$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";

Is there a similar syntax for an object

(object)$oVal = "";

$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";

Php Solutions


Solution 1 - Php

$x = new stdClass();

A comment in the manual sums it up best:

> stdClass is the default PHP object. > stdClass has no properties, methods or > parent. It does not support magic > methods, and implements no interfaces. > > When you cast a scalar or array as > Object, you get an instance of > stdClass. You can use stdClass > whenever you need a generic object > instance.

Solution 2 - Php

The standard way to create an "empty" object is:

$oVal = new stdClass();

But I personally prefer to use:

$oVal = (object)[];

It's shorter and I personally consider it clearer because stdClass could be misleading to novice programmers (i.e. "Hey, I want an object, not a class!"...).


(object)[] is equivalent to new stdClass().

See the PHP manual (here):

> stdClass: Created by typecasting to object.

and here:

> If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

and here (starting with PHP 7.3.0, var_export() exports an object casting an array with (object)):

> Now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState(). The practical effect is that now stdClass is exportable, and the resulting code will even work on earlier versions of PHP.


However remember that empty($oVal) returns false, as @PaulP said:

> Objects with no properties are no longer considered empty.

Regarding your example, if you write:

$oVal = new stdClass();
$oVal->key1->var1 = "something"; // this creates a warning with PHP < 8
                                 // and a fatal error with PHP >=8
$oVal->key1->var2 = "something else";

PHP < 8 creates the following Warning, implicitly creating the property key1 (an object itself) > Warning: Creating default object from empty value

PHP >= 8 creates the following Error: > Fatal error: Uncaught Error: Undefined constant "key1"

In my opinion your best option is:

$oVal = (object)[
  'key1' => (object)[
    'var1' => "something",
    'var2' => "something else",
  ],
];

Solution 3 - Php

I want to point out that in PHP there is no such thing like empty object in sense:

$obj = new stdClass();
var_dump(empty($obj)); // bool(false)

but of course $obj will be empty.

On other hand empty array mean empty in both cases

$arr = array();
var_dump(empty($arr));

Quote from changelog function empty > Objects with no properties are no longer considered empty.

Solution 4 - Php

Short answer

$myObj = new stdClass();

// OR 

$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

Long answer

I love how easy is to create objects of anonymous type in JavaScript:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value

So I always try to write this kind of objects in PHP like javascript does:

//PHP >= 5.4
$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

//PHP < 5.4
$myObj = (object) array(
    "foo" => "Foo value",
    "bar" => "Bar value"
);

echo $myObj->foo; //Output: Foo value

But as this is basically an array you can't do things like assign anonymous functions to a property like js does:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: function(greeting) {
        return greeting + " bar";
    }
};
console.log(myObj.bar("Hello")); //Output: Hello bar

//PHP >= 5.4
$myObj = (object) [
    "foo" => "Foo value",
    "bar" => function($greeting) {
        return $greeting . " bar";
    }
];
var_dump($myObj->bar("Hello")); //Throw 'undefined function' error
var_dump($myObj->bar); //Output: "object(Closure)"

Well, you can do it, but IMO isn't practical / clean:

$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar

Also, using this synthax you can find some funny surprises, but works fine for most cases.

Solution 5 - Php

php.net said it is best:

$new_empty_object = new stdClass();

Solution 6 - Php

In addition to zombat's answer if you keep forgetting stdClass

   function object(){
	
		return new stdClass();
		
	}

Now you can do:

$str='';
$array=array();
$object=object();

Solution 7 - Php

You can use new stdClass() (which is recommended):

$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);

// outputs:
// stdClass Object ( [name] => John ) 

Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:

$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);

// outputs: 
// stdClass Object ( [name] => John )  

Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:

$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);

// outputs:
// stdClass Object ( [name] => John ) 

Solution 8 - Php

Use a generic object and map key value pairs to it.

$oVal = new stdClass();
$oVal->key = $value

Or cast an array into an object

$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;

Solution 9 - Php

to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.

$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";

// then to acces it directly

echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};

// or what you may want

echo $myObj->{$myStringVar};

Solution 10 - Php

As others have pointed out, you can use stdClass. However I think it is cleaner without the (), like so:

$obj = new stdClass;

However based on the question, it seems like what you really want is to be able to add properties to an object on the fly. You don't need to use stdClass for that, although you can. Really you can use any class. Just create an object instance of any class and start setting properties. I like to create my own class whose name is simply o with some basic extended functionality that I like to use in these cases and is nice for extending from other classes. Basically it is my own base object class. I also like to have a function simply named o(). Like so:

class o {
  // some custom shared magic, constructor, properties, or methods here
}

function o() {
  return new o;
}

If you don't like to have your own base object type, you can simply have o() return a new stdClass. One advantage is that o is easier to remember than stdClass and is shorter, regardless of if you use it as a class name, function name, or both. Even if you don't have any code inside your o class, it is still easier to memorize than the awkwardly capitalized and named stdClass (which may invoke the idea of a 'sexually transmitted disease class'). If you do customize the o class, you might find a use for the o() function instead of the constructor syntax. It is a normal function that returns a value, which is less limited than a constructor. For example, a function name can be passed as a string to a function that accepts a callable parameter. A function also supports chaining. So you can do something like: $result= o($internal_value)->some_operation_or_conversion_on_this_value();

This is a great start for a base "language" to build other language layers upon with the top layer being written in full internal DSLs. This is similar to the lisp style of development, and PHP supports it way better than most people realize. I realize this is a bit of a tangent for the question, but the question touches on what I think is the base for fully utilizing the power of PHP.

Solution 11 - Php

If you want to create object (like in javascript) with dynamic properties, without receiving a warning of undefined property.

class stdClass {

public function __construct(array $arguments = array()) {
    if (!empty($arguments)) {
        foreach ($arguments as $property => $argument) {
            if(is_numeric($property)):
                $this->{$argument} = null;
            else:
                $this->{$property} = $argument;
            endif;
        }
    }
}

public function __call($method, $arguments) {
    $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
    if (isset($this->{$method}) && is_callable($this->{$method})) {
        return call_user_func_array($this->{$method}, $arguments);
    } else {
        throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
    }
}

public function __get($name){
    if(property_exists($this, $name)):
        return $this->{$name};
    else:
        return $this->{$name} = null;
    endif;
}

public function __set($name, $value) {
    $this->{$name} = $value;
}

}

$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value

$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null

Solution 12 - Php

You can try this way also.

<?php
     $obj = json_decode("{}"); 
     var_dump($obj);
?>

Output:

object(stdClass)#1 (0) { }

Solution 13 - Php

If you don't want to do this:

$myObj = new stdClass();
$myObj->key_1 = 'Hello';
$myObj->key_2 = 'Dolly';

You can use one of the following:

PHP >=5.4

$myObj = (object) [
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
];

PHP <5.4

$myObj = (object) array(
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
);

Solution 14 - Php

Here an example with the iteration:

<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";

foreach ($colors as $key => $value) : ?>
    <p style="background-color:<?= $value ?>">
        <?= $key ?> -> <?= $value ?>
    </p>
<?php endforeach; ?>

Solution 15 - Php

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)

Solution 16 - Php

You have this bad but usefull technic:

$var = json_decode(json_encode([]), FALSE);

Solution 17 - Php

You can also get an empty object by parsing JSON:

$blankObject= json_decode('{}');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioned209View Question on Stackoverflow
Solution 1 - PhpzombatView Answer on Stackoverflow
Solution 2 - PhpcgaldioloView Answer on Stackoverflow
Solution 3 - PhpPaulPView Answer on Stackoverflow
Solution 4 - PhpcampsjosView Answer on Stackoverflow
Solution 5 - PhpHungryCoderView Answer on Stackoverflow
Solution 6 - PhpRafaSashiView Answer on Stackoverflow
Solution 7 - PhpAmrView Answer on Stackoverflow
Solution 8 - PhpAnthony AwuleyView Answer on Stackoverflow
Solution 9 - PhpGCoroView Answer on Stackoverflow
Solution 10 - Phpstill_dreaming_1View Answer on Stackoverflow
Solution 11 - PhpfredtmaView Answer on Stackoverflow
Solution 12 - PhpMukesh JeengarView Answer on Stackoverflow
Solution 13 - PhpVasil NikolovView Answer on Stackoverflow
Solution 14 - PhpfingermanView Answer on Stackoverflow
Solution 15 - PhpLonareView Answer on Stackoverflow
Solution 16 - PhpKerollmopsView Answer on Stackoverflow
Solution 17 - PhpiamaspView Answer on Stackoverflow