Home >Backend Development >PHP Tutorial >PHP objects and resources_PHP tutorial
Object
Object initialization
To initialize an object, use the new statement to instance the object into a variable.
<?phpclass foo{ function do_foo() { echo "Doing foo."; }}$bar = new foo;$bar->do_foo();?> |
Convert to Object
If you convert an object to an object, it will not change anything. If a value of any other type is converted to an object, an instance of the built-in class stdClass will be created. If the value is NULL, the new instance is empty. For any other value, the member variable named scalar will contain the value.
<?php$obj = (object) 'ciao';echo $obj->scalar; // outputs 'ciao'?> |
Resources
A resource is a special variable that holds a reference to an external resource. Resources are created and used through specialized functions. All these functions and their corresponding resource types are provided in the appendix.
Note: Resource types were introduced in PHP 4.
Convert to Resource
Because resource type variables hold special handles for opening files, database connections, graphics canvas areas, etc., you cannot convert values of other types for resources.
Release resources
Since the PHP4 Zend engine introduces a resource counting system, it can automatically detect that a resource is no longer referenced (just like Java). In this case, all external resources used by this resource will be released by the garbage collection system. For this reason, it is rarely necessary to manually free memory using some free-result function.
Note: Persistent database connections are special, they will not be destroyed by the garbage collection system.