PHP学习笔记6:面向对象的PHP

读《PHP和MySQL Web开发》笔记合集:

http://my.oschina.net/bluefly/blog/478580

1、面向对象和类

在面向对象的程序中,对象是一个 被保存数据操作这些数据的操作方法的唯一、可标识的集合。
封装性、多态性(PHP中,只有类的成员函数可以试多态的,普通函数不支持)、集成。

2、特殊函数
比如构造函数(__construct())、析构函数(__destruct())、set、get等都是 双下划线__开头,双下划线表明在PHP中,这些函数具有特殊的意义,我们并不会直接访问这些函数。

3、this指针
在一个类中,可以访问一个特殊的指针$this.

4、修饰符
是否可以在类的外部访问一个属性,是有修饰符确定的。
public:不写的话,默认是这个。公有的属性或方法可以在类的内部和外部访问。
private:私有属性和方法只能在类内部访问,私有的属性和方法将不会被继承。
protected:被保护的属性和方法只能在类内部访问,但可以被继承。

5、extends继承 
PHP不支持多重集成,但是有“接口”这一特性
class B extends A
{
}

6、接口
如果需要实现多重继承,PHP中可以通过接口,接口可以看做是多重继承问题的解决方法,类似于其他面向对象编程语言所支持的接口实现,比如Java。
接口的思想是: 指定一个实现了该接口的类必须实现的一系列函数。
比如:
interface Displayable
{
function display();
}

class webPage implements Displayable
{
function display()
{
//
}
}
 
7、子类中重载
在子类中,再次声明相同的属性和操作也是有效的。
同时注意,parent关键字允许调用父类操作的最初版本,比如从B中调用A::operation,
parent::operation();

8、final关键字禁止继承和重载
可以放在函数前面,或者类前面,比如:
final function operation()  
{...}
函数不允许重载
final class A
{...}
类不循序重载

9、PHP结束和开始标记的灵活处理
如果函数体内部需要显示没有经过PHP处理的大量静态HTML,那么简单地使用PHP结束标记(?>)、输入HTML,然后再 在函数体内部使用一个PHP打开标记(<?php),例子:
public function DisplayStyles()
  { 
?>   
  <style>
    h1 {
        color:white; font-size:24pt; text-align:center; 
        font-family:arial,sans-serif
    }
    .menu {
        color:white; font-size:12pt; text-align:center; 
        font-family:arial,sans-serif; font-weight:bold
    }
    td {    
        background:black
    }
    p {
        color:black; font-size:12pt; text-align:justify; 
           font-family:arial,sans-serif
    }
    p.foot {
        color:white; font-size:9pt; text-align:center; 
        font-family:arial,sans-serif; font-weight:bold
    }
    a:link,a:visited,a:active {
        color:white
    }
  </style>
<?php
  }

10、使用动态脚本和静态页面取舍
用脚本穿件网页要求更多计算机处理器的处理操作,因为它并不是简单地从硬盘载入静态HTML页然后再送到浏览器。在一个业务繁忙的网站中,处理速度是很重要的,应该尽量使用静态HTML网页,或者尽可能缓存脚本输出,从而减少在服务器的载入操作。

11、理解PHP面向对象常量和静态
1)常量
Per-Class倡导的思想, 用const关键字,这个常量不需要初始化该类就可使用
<?php
class Math
{
const pi = 3.14159;
}
echo "Math::pi = ".Math::pi."\n";
?>
2)实现静态方法
<?php
class Math
{
static function squared($input)
{
    return $input*$input;
}
}
echo Math::squared(8);
?>
注意:在一个 静态方法中,不能使用this 关键字。因为可能会没有可以引用的对象实例。

12、检查类的类型
instanceof 关键字允许检查一个对象的类型,可以检查一个对象是否是特定类的实例,是否是从某个类继承过来的, 或者是否实现了某个接口。
instanceof  是一个高效率的条件操作符。
前提:类B继承于类A
{$b instanceof B} 将返回true,
{$b instanceof A} 将返回true,
{$b instanceof Displayable} 将返回false, 类B没有实现接口Displayable。

13、PHP类型提示
function check_hint(  B $someclass)
{
 //...
}
注意:通常,当在PHP中向一个函数传递一个参数时,不能传递该参数的类型。使用类类型提示,可以指定必须传入的参数类类型,否则将产生一个错误。类型检查等价于instanceof 的作用。
如果 check_hint( $a );
将产生如下致命错误:
Fatal error: Argument 1 must be an instance of B
注意:如果指定的是类A 而传入了B的实例,将不会产生任何错误,因为类B继承了类A。

14、延迟静态绑定
该特性(late static binding)允许在一个静态继承的上下文中对一个被调用类的引用。父类可以使用子类重载的静态方法。
<?php
class A
{
    public static function who()
        {
            echo __CLASS__;
        }
    public static function test()
        {
            static::who();  //here
        }

}

class B extends A
{
    public static function who()
        {
            echo __CLASS__;
        }
}

?>
B::test();
输出:
B

15、克隆对象
$c = clone $b;
将创建与对象$b 具有相同类的副本,而且具有相同的属性值。
注意:如果想改变这种行为,在基类中穿件一个__clone() 方法,这个方法类似于构造函数或者析构函数,因为不会直接调用,当使用clone关键字时,该方法被调用。
如果要克隆一个包含有对象引用的类,可能需要获得该对象的第二个副本,而不是第二个引用,所以这就是为什么要定制__clone()方法的原因。
                
16、抽象类
抽象类,这些类不能被实例化,类方法也没有实现。只用来被继承,确保每一个子类都包含并重载了某些特定的方法。
如抽象方法:
abstract operationX($param1, $param2);
包含抽象方法的任何类本身必须是抽象的:
abstract class A
{
    abstract operationX($param1, $param2);
}

17、使用__call() 重载方法
方法的重载在许多面向对象变成语言中都是非常常见的,但是在PHP中却不是非常有用,因为我们习惯使用灵活的类型和(容易实现)可选的函数参数。
要使用该方法,必须实现__call() 方法,如下例所示:
public function __call($method, $p)
{
    if ($method == "display")
    {
        if (is_object($p[0]))
        {
            $this->displayObject($p[0]));
        }
        else if (is_array($p[0]))
        {
            $this->displayArray($p[0]));
        }
        else
        {
            $this->displayScalar($p[0]));
        }

    }
}

__call()方法必须带有两个参数,第一个包含了被调用的方法名称,第二个参数包含了传递给该方法的参数数组。
注意:display()方法是不用实现的,其他几个方法按照我的理解,是要实现的。
调用实例:
$ov = new overload;
$ov->display(array(1,2,3));
$ov->display('cat');
第一个将调用displayArray(),第二个将调用displayScalar();。

18、__autoload()方法
这是一个单独的函数,不是一个类方法,可以在任何类声明之外声明这个函数。如果实现了该函数,它将在实例化一个还没有被声明的类时自动调用。去尝试包含或请求任何用来初始化所需类的文件。
例子:
function __autoload($name)
{
    include_once $name.".php";
}

19、实现迭代器和迭代
PHP的面向对象引擎,支持通过foreach()方法通过循环方式取出一个对象的所有属性,就像数组方式一样。例子:
class myClass
{
    public $a="5";
    public $b="7";
    public $c="9";
}
$x = new myClass;
foreach ($x as $attriute )
{
    echo $attriute."<br />";
}
如果需要一些更加复杂的行为,可以实现一个iterator(迭代器)。要实现一个迭代器,必须实现 IteratorAggregate接口,并且定义一个能够返回该类实例的getIterator方法。这个类必须实现Iterator接口。
<?php
class ObjectIterator implements Iterator {

   private $obj;
   private $count;
   private $currentIndex;

   function __construct($obj)
   {
     $this->obj = $obj;
     $this->count = count($this->obj->data);
   }
   function rewind()
   {
     $this->currentIndex = 0;
   }
   function valid()
   {
     return $this->currentIndex < $this->count;
   }
   function key()
   {
     return $this->currentIndex;
   }
   function current()
   {
     return $this->obj->data[$this->currentIndex];
   }
   function next()
   {
     $this->currentIndex++;
   }
}

class Object implements IteratorAggregate
{
  public $data = array();

  function __construct($in)
  {
    $this->data = $in;
  }

  function getIterator()
  {
    return new ObjectIterator($this);
  }
}

$myObject = new Object(array(2, 4, 6, 8, 10));

$myIterator = $myObject->getIterator();
for($myIterator->rewind(); $myIterator->valid(); $myIterator->next())
{
  $key = $myIterator->key();
  $value = $myIterator->current();
  echo $key." => ".$value."<br />";
}

?>



19、将类装换成字符串
如果在类中定义了一个__toString()函数,当尝试打印该类时,会调用这个函数。__toString()函数的 所有返回内容都将被echo语句打印。
用法如:
$p = new Printable;
echo $p;
实现如:
class Printable()
{
public $testone;
public $testtwo;
public function __toString()
    {
        return(var_export($this,TRUE));
    }
}

注意:var_export()函数打印出了类中的所有属性值。

20、使用Reflection(反射)API
反射是通过访问已有类和对象来找到类和对象的结构和内容的能力。
当使用未知或文档不详的类时,这个功能就非常游泳,比如经过编码的PHP脚本。
例子:
<?php

require_once("page.inc");

$class = new ReflectionClass("Page");
echo "<pre>".$class."</pre>";

?>

page.inc
<?php
class Page
{
  // class Page's attributes
  public $content;
  public $title = "TLA Consulting Pty Ltd";
  public $keywords = "TLA Consulting, Three Letter Abbreviation, 
                     some of my best friends are search engines";
  public $buttons = array("Home"   => "home.php", 
                        "Contact"  => "contact.php", 
                        "Services" => "services.php", 
                        "Site Map" => "map.php"
                    );

  // class Page's operations
  public function __set($name, $value)
  {
    $this->$name = $value;
  }

  public function Display()
  {
    echo "<html>\n<head>\n";
    $this -> DisplayTitle();
    $this -> DisplayKeywords();
    $this -> DisplayStyles();
    echo "</head>\n<body>\n";
    $this -> DisplayHeader();
    $this -> DisplayMenu($this->buttons);
    echo $this->content;
    $this -> DisplayFooter();
    echo "</body>\n</html>\n";
  }

  public function DisplayTitle()
  {
    echo "<title>".$this->title."</title>";
  }

  public function DisplayKeywords()
  {
    echo "<meta name=\"keywords\" 
          content=\"".$this->keywords."\"/>";
  }

  public function DisplayStyles()
  { 
?>   
  <style>
    h1 {
        color:white; font-size:24pt; text-align:center; 
        font-family:arial,sans-serif
    }
    .menu {
        color:white; font-size:12pt; text-align:center; 
        font-family:arial,sans-serif; font-weight:bold
    }
    td {    
        background:black
    }
    p {
        color:black; font-size:12pt; text-align:justify; 
           font-family:arial,sans-serif
    }
    p.foot {
        color:white; font-size:9pt; text-align:center; 
        font-family:arial,sans-serif; font-weight:bold
    }
    a:link,a:visited,a:active {
        color:white
    }
  </style>
<?php
  }

  public function DisplayHeader()
  { 
?>   
  <table width="100%" cellpadding="12" 
         cellspacing="0" border="0">
  <tr bgcolor ="black">
    <td align ="left"><img src = "logo.gif" /></td>
    <td>
        <h1>TLA Consulting Pty Ltd</h1>
    </td>
    <td align ="right"><img src = "logo.gif" /></td>
  </tr>
  </table>
<?php
  }

  public function DisplayMenu($buttons)
  {
    echo "<table width=\"100%\" bgcolor=\"white\" 
          cellpadding=\"4\" cellspacing=\"4\">\n";
    echo "<tr>\n";

    //calculate button size
    $width = 100/count($buttons);

    while (list($name, $url) = each($buttons)) {
      $this -> DisplayButton($width, $name, $url, 
               !$this->IsURLCurrentPage($url));
    }
    echo "</tr>\n";
    echo "</table>\n";
  }

  public function IsURLCurrentPage($url)
  {
    if(strpos($_SERVER['PHP_SELF'], $url )==false)
    {
      return false;
    }
    else
    {
      return true;
    }
  }

  public function 
      DisplayButton($width,$name,$url,$active = true)
  {
    if ($active) {
      echo "<td width = \"".$width."%\">
      <a href=\"".$url."\">
      <img src=\"s-logo.gif\" alt=\"".$name."\" border=\"0\" /></a>
      <a href=\"".$url."\"><span class=\"menu\">".$name."</span></a>
      </td>";
    } else {
      echo "<td width=\"".$width."%\">
      <img src=\"side-logo.gif\">
      <span class=\"menu\">".$name."</span>
      </td>";
    }  
  }

  public function DisplayFooter()
  {
?>
<table width="100%" bgcolor="black" cellpadding="12" border="0">
<tr>
<td>
    <p class="foot">&copy; TLA Consulting Pty Ltd.</p>
    <p class="foot">Please see our <a href ="">legal 
    information page</a></p>
</td>
</tr>
</table>
<?php
  }
}
?>
Class [  class Page ] {
  @@ D:\wamp\www\study\book\Chapter 06\page.inc 2-152

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [4] {
    Property [  public $content ] Property [  public $title ] Property [  public $keywords ] Property [  public $buttons ] } - Methods [10] { Method [  public method __set ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 16 - 19 - Parameters [2] { Parameter #0 [  $name ] Parameter #1 [  $value ] } } Method [  public method Display ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 21 - 33 } Method [  public method DisplayTitle ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 35 - 38 } Method [  public method DisplayKeywords ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 40 - 44 } Method [  public method DisplayStyles ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 46 - 74 } Method [  public method DisplayHeader ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 76 - 90 } Method [  public method DisplayMenu ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 92 - 107 - Parameters [1] { Parameter #0 [  $buttons ] } } Method [  public method IsURLCurrentPage ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 109 - 119 - Parameters [1] { Parameter #0 [  $url ] } } Method [  public method DisplayButton ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 122 - 136 - Parameters [4] { Parameter #0 [  $width ] Parameter #1 [  $name ] Parameter #2 [  $url ] Parameter #3 [  $active = true ] } } Method [  public method DisplayFooter ] { @@ D:\wamp\www\study\book\Chapter 06\page.inc 138 - 151 } } }

这里,使用了Reflection类的__toString()方法来打印这个数据。

转载于:https://my.oschina.net/bluefly/blog/522354

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值