認真學習php物件導向-1

來源:互聯網
上載者:User
認真學習php物件導向-1 前言

準備寫一個認真學習php物件導向的系列,使用php來做網頁,沒有深入瞭解php的話,可能三板斧就夠了,並不需要有多高深。如有錯誤,歡迎各位不吝賜教。進度安排的話,我學到哪裡,就更新到哪裡了。形式的話就採用一個需求小案例,然後實現,並附上自己的總結,文章源碼 主要完成工作 使用命令列模式類比編譯檔案以及建立檔案 實現簡單的網站骨架以及mvc路由偽編譯的作用 開篇所用到的環境

系統:ubuntu16.04
編輯器:phpstorm2017 需求 :1)在終端命令列下執行指令檔並輸入參數-v,然後顯示版本號碼 解決 : 需要用到php的預定義變數 argc和 argc和argv

argc和 argc和argv都是php的預定義變數,可以接收到命令列下下時傳遞給當前指令碼的參數的數組。argc是參數的個數,argv是傳遞給指令碼的參數數組 實現 :

$result='';if ($argc>=2) {    '-v'==$argv[1] && $result ='the version is 1.0';}echo $result;echo PHP_EOL;
效果 :

需求 :2)在終端命令列下執行指令檔並輸入參數init,在目前的目錄下產生一個json檔案 **解決 : file_put_contents,官網用法如下:

int file_put_contents ( string filename,mixed filename , mixed data [, int flags=0[,resource flags = 0 [, resource context ]] )
傳回值:該函數將返回寫入到檔案內資料的位元組數,失敗時返回FALSE 實現 :

$result='';    if ($argc>=2) {        '-v'==$argv[1] && $result ='the god version is 1.0';        '-init'==$argv[1] && $result =file_put_contents(getcwd().'/god.json','{}').' of bytes is written.'        .PHP_EOL.'god.json is created!';    }    echo $result;    echo PHP_EOL;
效果 :

需求 :3)判斷當前php版本 **解決 : substr函數,常量PHP_VERSION 實現 :

substr(PHP_VERSION,0,1);
效果 :

需求 :3)使用物件導向改造面向過程代碼 **解決 : 建立類,封裝函數 實現 : god_class.php

class god_calss{   static $version="the god version is 1.0";   static public function version() {       return self::$version;   }   static public function  getconfig() {       return file_put_contents(getcwd().'/god.json','{}').' of bytes is written.'    .PHP_EOL.'god.json is created!';   }}
god.php
require ("god_calss.php");    $result='';    if ($argc>=2) {        '-v'==$argv[1] && $result =god_calss::version();        '-init'==$argv[1] && $result =god_calss::getconfig();    }    echo $result;    echo PHP_EOL;
需求 :4)使用STDIN擷取命令列輸入 **解決 : fgets(從檔案指標中讀取一行),STDIN(標準輸入對象,c語言) 實現 : god_class.php
 static function init() {       echo "input your project_name?".PHP_EOL;       self::$prj_name=fgetc(STDIN);       echo  "input your author_name?".PHP_EOL;       self::$author=fgetc(STDIN);       echo "your input:";       echo self::$prj_name.PHP_EOL;       echo self::$author.PHP_EOL;   }
god.php
require ("god_calss.php");    $result='';    if ($argc>=2) {        '-v'==$argv[1] && $result =god_calss::version();        '-init'==$argv[1] && god_calss::init();    }    echo $result;    echo PHP_EOL;
效果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.