PostgreSQL & PHP Tutorials - Introduction to Object Oriented Programming

PHP »  Introduction to Object Oriented Programming

Posted By Chris Smith Posted on 19 Feb 2006, 07:13 AM
Viewing page 1 of 5
« | Back | Next | »

Object oriented programming is quite different to procedural programming, mainly in how you approach it.

Functional programming is good for basic scripts and programs. OOP is better suited to larger projects (though large projects work perfectly fine with functional programming), or projects where others can extend functionality or use your code as a base.

To start off, we'll look at how 'classes' work in PHP.


<?php
class {
    function 
__construct() {
        echo 
"I am in function " __FUNCTION__ "<br/>";
    }
}

$my_class = new a();

?>


The '__construct' function automatically gets run when you create a new object ($my_class = new a()). This could be used to set up a database connection.

Note - the '__construct' function is new in php5. To do the same in php4, name the function the same as the class:


<?php
class {
    function 
a() {
        echo 
"I am in function " __FUNCTION__ "<br/>";
    }
}

$my_class = new a();

?>


You could make your code backwards compatible:


<?php
class {

    function 
__construct() {
        
// this gets called in php5.
        
echo "I am in function " __FUNCTION__ "<br/>";
    }

    function 
a() {
        
// this gets called in php4.
        // we'll have to call the constructor ourselves.
        
$this->__construct();
    }
}

$my_class = new a();

?>
Viewing page 1 of 5
« | Back | Next | »



Avg Rating: 3
Vote Count: 28


              

  New Reply


I just have a comment/question. Why dont you implement abstract classes into this example rather than saying you cannot access update/delete etc. from the API class. I would make them abstract, explain a bit about what it is.

[ Editor's note - Interested in submitting an article about it? ]
Joseph Crawford 09 Jun 2006 Reply

This tutorial is very nice, I am trying to read up on creating my own API so the way you have structured things has helped a lot. Carlton Dickson 18 Jul 2007 Reply


Want to post a comment? Fill in the details below.

Your Name  : 
Your Email  : 
Your Website  : 
Spam Check! Please answer this question  : 8 + 2 =
Comment