Home arrow PHP arrow Page 6 - Object Oriented Programming in PHP

Object Oriented Programming in PHP

This article introduces Object Oriented Programming (OOP) in PHP. Luis shows you how to code less and better by using some OOP concepts and PHP tricks.

Author Info:
By: Luis Argerich
Rating: 4 stars4 stars4 stars4 stars4 stars / 356
January 13, 2003
  1. · Object Oriented Programming in PHP
  2. · Data Members and Functions
  3. · Constructors
  4. · Overloading
  5. · OOP Programming in PHP
  6. · Copying and Cloning
  7. · Conclusion

print this article

Object Oriented Programming in PHP - Copying and Cloning
(Page 6 of 7 )

When you create an object $obj you can copy the object by doing $obj2=$obj, the new object is a copy (not a reference) of $obj so it has the state $obj had in the moment the assignment was made.

Sometimes you don't want this you just want to create a new object of the same class as obj, calling the constructor of the new object as if you had used the new statement.

This can be done in PHP using serialization and a base class that all other classes must extend.

Entering a Danger Zone

When you serialize an object you get a string which has a certain format, you may investigate this if you are curious. One of the things the string has is the name of the class (nice!), you can extract it using:




So suppose you create a class "Universe" and force that all classes must extend universe, you can define a method clone in Universe as:


class Universe {
function clone() {
$ret=new $nam;
return $ret;


$obj=new Something();
//Something extends Universe !!


What you get is a new object of class Something created the same way as using new; the constructor is called, etc. I don't know if this is useful for you but the Universe class which knows the name of the derived class is a nice concept to experiment with. The only limit is your imagination.

Note: I'm using PHP4, some of these examples may not work in PHP3.
blog comments powered by Disqus

- Removing Singletons in PHP
- Singletons in PHP
- Implement Facebook Javascript SDK with PHP
- Making Usage Statistics in PHP
- Installing PHP under Windows: Further Config...
- File Version Management in PHP
- Statistical View of Data in a Clustered Bar ...
- Creating a Multi-File Upload Script in PHP
- Executing Microsoft SQL Server Stored Proced...
- Code 10x More Efficiently Using Data Access ...
- A Few Tips for Speeding Up PHP Code
- The Modular Web Page
- Quick E-Commerce with PHP and PayPal
- Regression Testing With JMeter
- Building an Iterator with PHP

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials