PostgreSQL & PHP Tutorials - Introduction to Object Oriented Programming
PHP »
Introduction to Object Oriented Programming
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 a {
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 a {
function a() {
echo "I am in function " . __FUNCTION__ . "<br/>";
}
}
$my_class = new a();
?>
You could make your code backwards compatible:
<?php
class a {
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: 4
Vote Count: 10
