Home  >  Article  >  php教程  >  PHP 5.0对象模型深度探索之属性和方法

PHP 5.0对象模型深度探索之属性和方法

WBOY
WBOYOriginal
2016-06-21 09:11:39923browse

对象

    一个对象实例的属性是变量,就像PHP的其他变量一样。但是你必须使用->运算符来引用它们。不需要在属性前使用美元符$。

  可以联用->,如果一个对象的属性包含了一个对象,你可以使用两个->运算符来得到内部对象的属性. 你甚至可以用双重引用的字符串来放置这些表达式. 下面的例子中,对象House中的属性room包含了一组Room对象。

  访问方法和访问属性类似。->运算符用来指向实例的方法. 在下面的中调用getLastLogin就是。方法执行起来和类外的函数几乎相同.

  如果一个类从另一类中继承而来,父类中的属性和方法将在子类中都有效,即使在子类中没有声明. 像以前提到过的,继承是非常强大的. 如果你想访问一个继承的属性,你只需要像访问基类自己的属性那样引用即可,使用::运算符.

class Room
{
 public $name;

 function __construct($name="unnamed")
 {
  $this->name = $name;
 }
}

class House
{
 //array of rooms
 public $room;
}

//create empty house
$home = new house;

//add some rooms
$home->room[] = new Room("bedroom");
$home->room[] = new Room("kitchen");
$home->room[] = new Room("bathroom");

//show the first room of the house
print($home->room[0]->name);
?>
  PHP有两个特殊的命名空间:parent命名空间指向父类,self命名空间指向当前的类。下面的例子中显示了如何用parent命名空间来调用父类中的构造函数. 同时也用self来在构造函数中调用另一个类方法。

class Animal //动物
{
 public $blood; //热血or冷血属性
 public $name;
 public function __construct($blood, $name=NULL)
 {
  $this->blood = $blood;
  if($name)
  {
   $this->name = $name;
  }
 }
}

class Mammal extends Animal //哺乳动物
{
 public $furColor; //皮毛颜色
 public $legs;

 function __construct($furColor, $legs, $name=NULL)
 {
  parent::__construct("warm", $name);
  $this->furColor = $furColor;
  $this->legs = $legs;
 }
}

class Dog extends Mammal
{
 function __construct($furColor, $name)
 {
  parent::__construct($furColor, 4, $name);

  self::bark();
 }

 function bark()
 {
  print("$this->name says 'woof!'");
 }
}

$d = new Dog("Black and Tan", "Angus");
?>
  对于对象的成员来是这样调用的:如果你需要在运行时确定变量的名称,你可以用$this->$Property这样的表达式。 如果你想调用方法,可以用$obj->$method()。

  你也可以用->运算符来返回一个函数的值,这在PHP以前的版本中是不允许的。例如,你可以写一个像这样的表达式: $obj->getObject()->callMethod()。这样避免了使用一个中间变量,也有助于实现某些设计模式,如Factory模式。



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn