Objects
Objects
Object Initialization
To create a new , use the statement
to instantiate a class:
object``new
Voorbeeld: Object Construction
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
For a full discussion, see the chapter. Classes and Objects
Converting to object
If an is converted to an , it is not
modified. If a value of any other type is converted to an
, a new instance of the
built-in class is created. If the value was null, the new instance will be
empty. An converts to an 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.
object``object``object``stdClass``array``object
Voorbeeld: 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 will contain
the value.
scalar
Voorbeeld: cast
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>