第1次亲密接触PHP5(1)

2019-04-07 19:26:02王振洲

if($o1->getX() == $o2->getX()) print("Oh my god!");
?>

(二泉 注:你将看到"Oh my god!"的输出)
克隆对象

如上,如果有时不想得到对象的引用而想用copy时,怎么办?在PHP5提供的 __clone 方法中实现:
例3:克隆对象

<?php
class foo {
  var $x;

  function setX($x) {
    $this->x = $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");
?>

克隆对象的方法在已被应用到很多语言中,所以你不必担心它的性能:)。

Private, Public 和 Protected

在PHP4中,你可以在对象的外面操作它任意的方法和变量--因为方法和变量是公用的。在PHP5引用了3种模式来控制
对变量、方法的控制权限:Public(公用的)、Protected(受保护)和Private(私有)

Public:方法和变量可以在任意的时候被访问到
Private:只能在类的内部被访问,子类也不能访问
Protected:只能在类的内部、子类中被访问

例子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->x = 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();
?>


提示:变量总是私有形式,直接访问一个私有变量并不是一个好的OOP思想,应该用其他的方法来实现 set/get 的功能


接口

正如你知道的一样,在 PHP4 中实现继承的语法是"class foo extends parent"。无论在PHP4 还是在 PHP5 中,都不支持多重继承即只能从一个类往下继承。 PHP5中的"接口"是这样的一种特殊的类:它并不具体实现某个方法,只是用来定义方法的名称和拥有的元素,然后通过关键字将它们一起引用并实现具体的动作。
相关文章 大家在看