PHPBuilder - Introduction to PHP5 Page 3



RSS Twitter
Articles Tricks And Hacks

Introduction to PHP5 - Page 3

by: Luis Argerich
|
April 11, 2003

Cloning objects

Since objects are passed and assigned as references you need some way to create a copy of an object. Enter the __clone method.
Example 3: Cloning objects

<?php
class foo {
  var 
$x;

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

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

$o1 = new foo;
$o1->setX(4);
$o2 $o1->__clone();
$o1->setX(5);

if(
$o1->getX() != $o2->getX()) print("Copies are independant");
?>
Cloning is ok in programming languages, don't feel guilty ;-)
In PHP4 all the methods and variables in an Object can be accessed from outside the object - this can be rephrased as methods and variables are always public. PHP5 introduces 3 modifiers to control the access to variables and methods: Public, Protected and Private.
Public: The method/variable can be accessed from outside the class.
Private: Only methods in the same class can access private methods or variables.
Protected: Only methods in the same class or derived classes can access proteted methods or variables.
Example 4: Public, protected and private

<?php
class foo {
  private 
$x;

  public function 
public_foo() {
    print(
"I'm public");
  }

  protected function 
protected_foo() {
    
$this->private_foo(); //Ok because we are in the same class we can call private methods
    
print("I'm protected");
  }

  private function 
private_foo() {
    
$this->3;
    print(
"I'm private");
  }
}

class 
foo2 extends foo {
  public function 
display() {
    
$this->protected_foo();
    
$this->public_foo();
    
// $this->private_foo();  // Invalid! the function is private in the base class
  
}
}

$x = new foo();
$x->public_foo();
//$x->protected_foo();  //Invalid cannot call protected methods outside the class and derived classes
//$x->private_foo();    //Invalid private methods can only be used inside the class

$x2 = new foo2();
$x2->display();
?>
Design tip: Variables should always be private, accessing variables is not a good OOP practice, it is always better to provide methods to get/set the variables.

« 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.