PHP面向過程和物件導向

來源:互聯網
上載者:User

標籤:

 php程式編寫分為面向過程和物件導向。兩者在功能實現上沒有區別,但是在代碼編寫上區別很大,面向過程的代碼很亂,不易管理,而物件導向把常用的功能封裝為一個類,這樣代碼清楚多了。

    下面舉個小例子說明一下:

php串連資料庫:

面向過程:$conn = mysql_connect(‘伺服器名稱‘, ‘資料庫登陸名‘, ‘密碼‘) or die(‘串連不成功!‘);
          mysql_select_db(‘庫名‘, $conn) or die(‘資料庫不存在!‘);
          $queryid = mysql_query("select * from sort");
          while ($rs = mysql_fetch_assoc($queryid)) {
          echo $rs[‘name‘], ‘<br>‘;

物件導向:1.建個php檔案叫db.php,把上面的代碼封裝成一個類:

         class db {
             private $conn; //屬性
             private $queryid; //屬性
             //建構函式
             public function db($host, $dbuser, $dbpasswd, $dbname) {
             $this->conn = mysql_connect($host, $dbuser, $dbpasswd) or die(‘串連不成功!‘);
             mysql_select_db($dbname, $this->conn) or die(‘資料庫不存在!‘);
        }
        //查詢方法
       public function query($sql) {
        $this->queryid = mysql_query($sql, $this->conn);
       }
       public function fetch_assoc() {
        return mysql_fetch_assoc($this->queryid);
       }
       }

       2.在a.php檔案中執行個體化,代碼使用變得簡結和容易理解,代碼的重用性
          inclode(‘db.php‘);
          $db = new db(‘伺服器名‘, ‘資料庫登入名稱‘, ‘密碼‘, ‘庫名‘);
          $db->query("select * from sort");
          while ($rs = $db->fetch_assoc()) {
              echo $rs[‘name‘], ‘<br>‘;
          }

PHP面向過程和物件導向

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.