PHPBuilder - Introduction to PHP5 Page 2



RSS Twitter
Articles Tricks And Hacks

Introduction to PHP5 - Page 2

by: Luis Argerich
|
April 11, 2003

The new object model

The PHP5 object model has been revamped adding a lot of features that will give PHP5 a Java flavour. The following section of this article will describe this new object model and some quick examples that you can use as a starting point for your experiments.
  • Constructors and destructors
  • Objects as references
  • Cloning objects
  • Private, Public and Protected keywords
  • Interfaces
  • Abstract classes
  • __call
  • __set and __get
  • Static members

Constructors and Destructors

In PHP4 constructors are named as the class and there are no destructors.
In PHP5 the constructor for a class is called __construct and the destructor is called __destruct.
Example 1: Constructors and destructors

<?php
class foo {
  var 
$x;

  function 
__construct($x) {
    
$this->$x;
  }

  function 
display() {
    print(
$this->x);
  }

  function 
__destruct() {
    print(
"bye bye");
  }
}

$o1 = new foo(4);
$o1->display();
?>
As you will see the destructor will be called just before the object is eliminated.

Objects as References

In PHP4 as you may already know variables are passed to functions/methods by value (a copy is passed) unless you use the '&' symbol in the function declaration indicating that the variable will be passed as a reference. In PHP5 objects will be passed always as references. Object assignation is also done by reference.
Example 2: Objects as references

<?php
class foo {
  var 
$x;

  function 
setX($x) {
    
$this->$x;
  }

  function 
getX() {
    return 
$this->x;
  }
}

$o1 = new foo;
$o1->setX(4);
$o2 $o1;
$o1->setX(5);
if(
$o1->getX() == $o2->getX()) print("Oh my god!");
?>

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Luis Argerich

Comment:



Comment:

(Maximum characters: 1200). You have characters left.