PHP面向对象入门

理解OOP

OOP是一种更直观的抽象,把一些功能和属性相似的抽象成一个类。可以减少重复代码。

理解对象和类

类的实例化就是对象,对象是某一个具体的东西。


类和对象

定义类属性

定义类方法

prop1 = $newval;
  }
 
  public function getProperty()
  {
      return $this->prop1 . "
"; } } $obj = new MyClass; echo $obj->prop1; ?>

魔术方法(magic methods)

构造方法(constructors)和析构方法(destructors)

';
  }
 
  public function __destruct()
  {
      echo 'The class "', __CLASS__, '" was destroyed.
'; } public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "
"; } } // Create a new object $obj = new MyClass; // Get the value of $prop1 echo $obj->getProperty(); // Destroy the object unset($obj); // Output a message at the end of the file echo "End of file.
"; ?>

字符串转换

';
  }
 
  public function __destruct()
  {
      echo 'The class "', __CLASS__, '" was destroyed.
'; } public function __toString() { echo "Using the toString method: "; return $this->getProperty(); } public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1 . "
"; } } // Create a new object $obj = new MyClass; // Output the object as a string echo $obj; // Destroy the object unset($obj); // Output a message at the end of the file echo "End of file.
"; ?>

类的继承

class1 extend class2

重写父类方法

保留父类方法

parent::method()

属性和方法的可见性

public
protected
private

静态属性和方法 (static)

注释

对比面向对象和面向过程

方便使用

更好组织

方便维护

你可能感兴趣的:(PHP面向对象入门)