Hướng dẫn php create empty object

with a new array I do this:

Show
$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";

Sumurai8

19.8k10 gold badges69 silver badges97 bronze badges

asked Sep 16, 2009 at 17:24

2

$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.

answered Sep 16, 2009 at 17:24

Hướng dẫn php create empty object

zombatzombat

90.9k24 gold badges155 silver badges164 bronze badges

7

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",
  ],
];

answered Mar 19, 2015 at 14:19

cgaldiolocgaldiolo

3,1071 gold badge19 silver badges17 bronze badges

11

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.

answered Aug 26, 2011 at 14:04

PaulPPaulP

1,8952 gold badges20 silver badges25 bronze badges

2

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.

answered Jan 14, 2016 at 10:47

campsjoscampsjos

1,13314 silver badges21 bronze badges

0

php.net said it is best:

$new_empty_object = new stdClass();

GateKiller

72.2k72 gold badges170 silver badges204 bronze badges

answered Sep 12, 2010 at 5:18

HungryCoderHungryCoder

7,4561 gold badge37 silver badges50 bronze badges

1

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();

answered Jan 30, 2015 at 12:27

Hướng dẫn php create empty object

RafaSashiRafaSashi

15.7k8 gold badges79 silver badges90 bronze badges

1

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 ) 

answered Dec 14, 2015 at 0:57

Hướng dẫn php create empty object

AmrAmr

4,3536 gold badges44 silver badges58 bronze badges

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;

answered Jun 16, 2017 at 20:50

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};

answered Feb 20, 2015 at 9:04

GCoroGCoro

711 silver badge2 bronze badges

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

answered Nov 26, 2015 at 15:02

Hướng dẫn php create empty object

fredtmafredtma

9971 gold badge15 silver badges25 bronze badges

You can try this way also.

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

Output:

object(stdClass)#1 (0) { }

answered Nov 24, 2016 at 9:36

As others have pointed out, you can use 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.

EDIT/UPDATE: I no longer recommend any of this. It makes it hard for static analysis tools and IDEs and custom AST based tools to understand, validate, help you lookup or write your code. Generally magic is bad except in some cases if you are able to get your tools to understand the magic and if it you do it in a standard enough way that even standard community tools will understand it or if your tools are so advanced and full featured that you only use your own tools. Also, I think they are deprecating the ability to add properties to random objects in an upcoming version of PHP, I think it will only work with certain ones, but I don't recommend using that feature anyways.

answered Aug 27, 2014 at 1:03

still_dreaming_1still_dreaming_1

8,1676 gold badges39 silver badges53 bronze badges

3

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',
);

answered Jan 31, 2017 at 10:22

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; ?>

answered Feb 3, 2017 at 18:31

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)

answered Nov 28, 2019 at 9:47

LonareLonare

3,96833 silver badges40 bronze badges

You have this bad but usefull technic:

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

answered Jun 12, 2014 at 21:37

KerollmopsKerollmops

1933 silver badges15 bronze badges

0

You can also get an empty object by parsing JSON:

$blankObject= json_decode('{}');

Hướng dẫn php create empty object

Dharman

27.8k21 gold badges75 silver badges126 bronze badges

answered Jan 7, 2021 at 6:01

Hướng dẫn php create empty object

1