HomePHP Page 3 - Using Inheritance, Polymorphism and Serialization with PHP Classes
Class Functions Without Instances - PHP
If you are working with classes in PHP, you will sooner or later encounter inheritance, polymorphism, and serialization. The ability to use these three will help speed up your code writing. This article covers how to use them, and more.
There is a way to use a class function without having to create an instance of a class. This capability has been added since PHP 4 and is useful if you only need a function from a class, but not the entire class itself. The syntax for doing this is:
the_Classname::the_Method();
To demonstrate, lets use the "say_hello()" function in our human class:
<? class human{ function human($hcolor){ $this->hcolor=$hcolor; } function say_hello(){ echo "Hello!<br>"; } } echo "The result of the uninstantiated class function is: <br>"; echo herehuman::say_hello(); ?>
As you can see from the code above, all I did was add the human::say_hello() line of code. The say_hello() function is a function of the human class. Normally, to use this function we would have to create an instance of the class, but in this case we did not, so let’s run the code and see what happens:
The above screen shot shows the results of a class function used without instantiating the class.
Remember to include the class from which you want to use the method. Also, as a matter of good coding practice, you can make sure the specific function exists in a class before using it. You do this like so:
In most object oriented languages there is a built-in capability to free or destroy objects that you no longer want to use. Why do you need to destroy an object? Well, the reason is quite simple. The creation and use of an object is resource intensive, and it is therefore important to free up the resources that get tied up when using objects. This is done by calling the unset() function after you’ve instantiated the object:
$object = new Classname unset($object);
Remember to call this function at the very end of a script to avoid destroying the object while it is needed by the program.