Tips on OOP in PHP

Feedback to the Blender Foundation and the moderators of this website

Moderators: jesterKing, stiv

Post Reply
Posts: 320
Joined: Sun Oct 27, 2002 6:45 am

Tips on OOP in PHP

Post by thorax » Mon Apr 07, 2003 10:50 am

I guess I tend to volunteer information that I find out, some may
be a little mad at me since I do this, but sometimes I have problems
and look around to find few know what the solution is.. I did not
find this in much PHP books, it was on the website..

When making PHP objects:

class objectA {

var $a;

function objectA($b) { // this is a constructor
$this->a = $b;

function get () {
return $this->a;


class objectB {

var $childA;

function objectB($a) {
$childA =& new objectA($a);

function printA() {
print $this->childA->get();


$test =& new objectB("hello OOP world");

print $test->childA->get();

The trick is using that "&", the only problem is that
it doesn't use pointers, this is just a hard link, so it can't be used for linked lists..

The way this could be used in the website:

class Session {
var $sessionvars;

function Session($stuff) {
// stuff brought in from login object, sets maybe the transaction
// type, whether using a cookie, what vars should be created,
// access level, etc..

function _sleep() {
// put code here to prepare saving of session vars..

function _wake() {
// put code for restoring of session vars..


Then you could use "serialize" to store and restore the session object
and whatever else needs to be stored in the database.. To be restored
later.. You probably already know this, I'm just saying I didn't know about the OOP stuff in PHP until only recently.. I hope it helps..

There is also an "extends" option for classes, which helps in
inheritance, but PHP is far from OOP complete, its just better than
going around defining global functions are vars.. I spent a day converting all my functional code and globals to OOP, but once I converted,
it became a lot easier to debug and track the function calls..
Using "error_log".. I'm going to create an object for "error_log"
so that I don't have to annotate which function in which class
has the error and just have to type
$debug->print("something went wrong here").

Post Reply