To create a new object, use the new
statement to instantiate a class:
Example #1 Object Construction
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}$bar = new foo;
$bar->do_foo();
?>
For a full discussion, see the Classes and Objects chapter.
Converting to objectIf 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. If the value was null
, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values. Note that in this case before PHP 7.2.0 numeric keys have been inaccessible unless iterated.
Example #2 Casting to an Object
<?php
$obj = (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // outputs 'bool(true)'
// Deprecated as of PHP 8.1
var_dump(key($obj)); // outputs 'string(1) "1"'
?>
For any other value, a member variable named scalar
will contain the value.
Example #3 (object)
cast
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>
13 years ago
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:
<?php $genericObject = new stdClass(); ?>
I had the most difficult time finding this, hopefully it will help someone else!
Anthony ¶
9 years ago
In PHP 7 there are a few ways to create an empty object:
<?php
$obj1 = new \stdClass; $obj2 = new class{}; $obj3 = (object)[]; var_dump($obj1); var_dump($obj2); var_dump($obj3); ?>
$obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:
<?php
echo json_encode([
new \stdClass,
new class{},
(object)[],
]);
?>
Outputs: [{},{},{}]
twitter/matt2000 ¶
10 years ago
As of PHP 5.4, we can create stdClass objects with some properties and values using the more beautiful form:
<?php
$object = (object) [
'propertyOne' => 'foo',
'propertyTwo' => 42,
];
?>
Ashley Dambra ¶
11 years ago
Here a new updated version of 'stdObject' class. It's very useful when extends to controller on MVC design pattern, user can create it's own class.
Hope it help you.
<?php
class stdObject {
public function __construct(array $arguments = array()) {
if (!empty($arguments)) {
foreach ($arguments as $property => $argument) {
$this->{$property} = $argument;
}
}
}
public function
__call($method, $arguments) {
$arguments = array_merge(array("stdObject" => $this), $arguments); 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}()");
}
}
}$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;$obj->getInfo = function($stdObject) { echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};$func = "setAge";
$obj->{$func} = function($stdObject, $age) { $stdObject->age = $age;
};$obj->setAge(24); foreach ($obj as $func_name => $value) {
if (!$value instanceOf Closure) {$obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) { $stdObject->{$func_name} = $value;
};$obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) { return $stdObject->{$func_name};
};
}
}$obj->setName("John");
$obj->setAdresse("Boston");$obj->getInfo();
?>
developer dot amankr at gmail dot com (Aman Kuma) ¶
9 years ago
<!--Example shows how to convert array to stdClass Object and how to access its value for display -->
<?php
$num = array("Garha","sitamarhi","canada","patna"); $obj = (object)$num; echo "<pre>";
print_r($obj); $newobj = new stdClass();$newobj->name = "India";
$newobj->work = "Development";
$newobj->address="patna";$new = (array)$newobj;echo "<pre>";
print_r($new); $test = [Details=>['name','roll number','college','mobile'],values=>['Naman Kumar','100790310868','Pune college','9988707202']];
$val = json_decode(json_encode($test),false);echo "<pre>";
print_r($val);
echo ((
is_array($val) == true ? 1 : 0 ) == 1 ? "array" : "not an array" )."</br>"; echo ((is_object($val) == true ? 1 : 0 ) == 1 ? "object" : "not an object" );?>
qeremy [atta] gmail [dotta] com ¶
13 years ago
Do you remember some JavaScript implementations?
// var timestamp = (new Date).getTime();
Now it's possible with PHP 5.4.*;
<?php
class Foo
{
public $a = "I'm a!";
public $b = "I'm b!";
public $c;
public function
getB() {
return $this->b;
}
public function
setC($c) {
$this->c = $c;
return $this;
}
public function
getC() {
return $this->c;
}
}
print (new
Foo)->a; print (new Foo)->getB(); ?>
or
<?php
print (new Foo)
->setC($_GET["c"])
->getC(); ?>
mailto dot aurelian at gmail dot com ¶
15 years ago
You can create [recursive] objects with something like:
<?php
$literalObjectDeclared = (object) array(
'foo' => (object) array(
'bar' => 'baz',
'pax' => 'vax'
),
'moo' => 'ui'
);
print $literalObjectDeclared->foo->bar; ?>
16 years ago
In response to harmor: if an array contains another array as a value, you can recursively convert all arrays with:
<?php
function arrayToObject( $array ){
foreach( $array as $key => $value ){
if( is_array( $value ) ) $array[ $key ] = arrayToObject( $value );
}
return (object) $array;
}
?>
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3