<?php interface IHuman { function GetName(); } class ManClass implements IHuman { public function GetName() { return "I'm man."."<br>"; } } class WomanClass implements IHuman { public function GetName() { return "I'm Woman."."<br>"; } }在物件導向程式設計中, 最通常的方法是一個new操作符產生一個物件實例,new操作符就是用來建構物件實例的。但是在一些情況下, new操作符直接產生物件會帶來一些問題。舉例來說, 許多類型物件的創造需要一系列的步驟: 你可能需要計算或取得物件的初始設定; 選擇生成哪個子物件實例; 或在生成你需要的物件之前必須先生成一些輔助功能的物件。在這些情況,新物件的建立就是一個 “過程”,不僅是一個操作,像一部大機器中的一個齒輪傳動。
<?php public function setEncode($incode,$outcode){ $this->inEncode=$incode; $this->outEncode=$outcode; } public function setTitle($titlearr){ $title=""; foreach($titlearr as $v){ if($this->inEncode!=$this->outEncode){ $title.=iconv($this->inEncode,$this->outEncode,$v)."\t"; } else{ $title.=$v."\t"; } } $title.="\n"; return $title; }使用方法$excel=new Excel();設定編碼:$excel->setEncode("utf-8" ,"gb2312"); //若不轉碼,參數寫一樣即可,例如$excel->setEncode("utf-8","utf-8");#設定標題列$titlearr=array("a","b","c","d");設定內容欄$contentarr=array(1=>array("ab","ac","ad","ae"),#2=>array( "abc","acc","adc","aec"),3=>array("abd","acd","add","aed"),#4=>array("abe","ace","ade","aee"), ); $excel->getExcel($titlearr,$ contentarr,"abc");#
<?php class Foo { const BAR = 'bar'; public static function getConstantValue() { return self::BAR; } public function getConstant() { return self::BAR; } } $foo = 'Foo'; echo $foo::BAR, '<br />'; echo Foo::BAR, '<br />'; $obj = new Foo(); echo $obj->getConstant(), '<br />'; echo $obj->getConstantValue(), '<br />'; echo Foo::getConstantValue(); class Bar extends Foo { const BAR = 'foo'; public static function getMyConstant() { return self::BAR; } public static function getParentConstant() { return parent::BAR; } } echo Bar::getMyConstant(); // foo echo Bar::getParentConstant(); // bar類別常數屬於類別自身,不屬於物件實例,不能透過物件實例存取不能用public,protected,private,static修飾子類別可以重寫父類別中的常數,可以透過(parent::)來呼叫父類別中的常數 自PHP5.3.0起,可以用一個變數來動態呼叫類別。但該變數的值不能為關鍵字
<?php class time{ private $year;//年 private $month;//月 private $day;//天 private $hour;//小时 private $minute;//分钟 private $second;//秒 private $weekday;//星期 private $longDate;//完整的时间格式 private $diffTime;//两个时间的差值 //返回年份 time:时间格式为时间戳 2016-8-27 function getyear($time="",$type=""){ if($time==""){ $time=time(); } if($type==1){ return $this->year=date("y",$time); //返回两位的年份 16 }else{ return $this->year=date("Y",$time); //返回四位的年份 2016 } } //返回当前时间的月份 time:时间格式为时间戳 2016-8-27 function getmonth($time="",$type=""){ if($time==""){ $time=time(); }PHP時間類完整實例,涉及PHP針對日期、時間、星期等的獲取與比較等等各種操作技巧,非常簡單實用,需要的朋友可以參考下,方便大家學習體會php的程式碼。
<?php header("Content-Type: text/html; charset=UTF-8"); require("phpQuery.php"); $hj = QueryList::Query('http://mobile.csdn.net/',array("title"=>array('.unit h1','text'))); //dump($hj->data); $data = QueryList::Query('http://cms.querylist.cc/bizhi/453.html',array( 'image' => array('img','src') ))->data; // $data = QueryList::Query('http://cms.querylist.cc/google/list_1.html',array( 'link' => array('a','href') ))->data; $page = 'http://cms.querylist.cc/news/566.html'; $reg = array( 'title' => array('h1','text'), 'date' => array('.pt_info','text','-span -a',function($content){ $arr = explode(' ',$content); return $arr[0]; }), 'content' => array('.post_content','html','a -.content_copyright -script',function($content){ $doc = phpQuery::newDocumentHTML($content); $imgs = pq($doc)->find('img'); foreach ($imgs as $img) { $src = 'http://cms.querylist.cc'.pq($img)->attr('src'); $localSrc = 'w/'.md5($src).'.jpg'; $stream = file_get_contents($src); file_put_contents($localSrc,$stream); pq($img)->attr('src',$localSrc); } return $doc->htmlOuter(); }) ); $rang = '.content'; $ql = QueryList::Query($page,$reg,$rang); $data = $ql->getData(); dump($data);支援抓取網站,進行爬蟲,非常強大,是一個基於PHP的服務端開源項目,它可以讓PHP開發人員輕鬆處理DOM文檔內容,例如獲取某新聞網站的頭條信息。更有趣的是,它採用了jQuery的思想,你可以像使用jQuery一樣處理頁面內容,獲得你想要的頁面資訊。
<?php header("Content-Type:text/html; charset=utf-8"); define('APP_ROOT', str_replace('\', '/', dirname(__FILE__))); function get_tags_arr($title) { require(APP_ROOT.'/pscws4.class.php'); $pscws = new PSCWS4(); $pscws->set_dict(APP_ROOT.'/scws/dict.utf8.xdb'); $pscws->set_rule(APP_ROOT.'/scws/rules.utf8.ini'); $pscws->set_ignore(true); $pscws->send_text($title); $words = $pscws->get_tops(5); $tags = array(); foreach ($words as $val) { $tags[] = $val['word']; } $pscws->close(); return $tags; } print_r(get_tags_arr($con)); function get_keywords_str($content){ require(APP_ROOT.'/phpanalysis.class.php'); PhpAnalysis::$loadInit = false; $pa = new PhpAnalysis('utf-8', 'utf-8', false); $pa->LoadDict(); $pa->SetSource($content); $pa->StartAnalysis( false ); $tags = $pa->GetFinallyResult(); return $tags; } print(get_keywords_str($con));不需要安裝擴展,自帶字典,使用方法簡單採用很多人熟知的scws,另一個是IT柏拉圖做的phpanalysis使用方法請參考index.php檔案範例
<?php class Cart { //物品id及名称规则,调试信息控制 private $product_id_rule = '\.a-z0-9-_'; //小写字母 | 数字 | ._- private $product_name_rule = '\.\:a-z0-9-_';//小写字母 | 数字 | ._-: private $debug = TRUE; private $_cart_contents = array(); public function __construct() { //是否第一次使用? if(isset($_SESSION['cart_contents'])) { $this->_cart_contents = $_SESSION['cart_contents']; } else { $this->_cart_contents['cart_total'] = 0; $this->_cart_contents['total_items'] = 0; } if($this->debug === TRUE) { //$this->_log("cart_create_success"); } }PHP的購物車類別庫,主要介紹了PHP實現的購物車類,可實現購物車基本的加入、刪除、統計等相關功能,購物車基本功能如下:1) 將物品加入購物車 2) 從購物車中刪除物品 3) 更新購物車物品資訊【 1/-1】 4) 對購物車物品進行統計 1. 總項目 2. 總數量 3. 總金額 5) 購物單項物品的數量及金額進行統計 6) 清空購物
<?php class ftp { public $off; // 返回操作状态(成功/失败) public $conn_id; // FTP连接 function __construct($FTP_HOST,$FTP_PORT,$FTP_USER,$FTP_PASS) { $this->conn_id = @ftp_connect($FTP_HOST,$FTP_PORT) or die("FTP服务器连接失败"); @ftp_login($this->conn_id,$FTP_USER,$FTP_PASS) or die("FTP服务器登陆失败"); @ftp_pasv($this->conn_id,1); // 打开被动模拟 } function up_file($path,$newpath,$type=true) { if($type) $this->dir_mkdirs($newpath); $this->off = @ftp_put($this->conn_id,$newpath,$path,FTP_BINARY); if(!$this->off) echo "文件上传失败,请检查权限及路径是否正确!"; }方法:FTP連線@FTP_HOST -- FTP主機#@FTP_PORT -- 埠@FTP_USER -- 使用者名稱@ FTP_PASS -- 密碼
<?php namespace Moontoast\Math; class BigNumberTest extends \PHPUnit_Framework_TestCase { protected function setUp() { ini_set('bcmath.scale', 0); } /** * @covers Moontoast\Math\BigNumber::__construct * @covers Moontoast\Math\BigNumber::getValue * @covers Moontoast\Math\BigNumber::getScale * @covers Moontoast\Math\BigNumber::setValue * @covers Moontoast\Math\BigNumber::filterNumber * @covers Moontoast\Math\BigNumber::setDefaultScale */ public function testConstruct() { $bn1 = new BigNumber('9,223,372,036,854,775,808'); $this->assertSame('9223372036854775808', $bn1->getValue()); $this->assertEquals(0, $bn1->getScale()); $bn2 = new BigNumber(2147483647); $this->assertSame('2147483647', $bn2->getValue()); $this->assertEquals(0, $bn2->getScale());這是一份處理特大數字的PHP函式庫,需要的朋友可以下載使用。
<?php require_once __DIR__.'/../vendor/autoload.php'; use HeyUpdate\Emoji\UnicodeUtil; $configFile = __DIR__.'/../config/index.json'; $template = <<<'TEMPLATE namespace HeyUpdate\Emoji\Index; class CompiledIndex extends BaseIndex { protected $emojis = {{emojis}}; protected $emojiUnicodes = {{emojiUnicodes}}; /** * @var array */ protected $emojiNames = {{emojiNames}}; /** * @var string */ protected $emojiUnicodeRegex = {{emojiUnicodeRegex}}; /** * @var string */ protected $emojiNameRegex = {{emojiNameRegex}}; }這是一份處理emoji的PHP類別庫,需要的朋友可以下載使用。
<?php namespace SensioLabs\AnsiConverter\Tests; use SensioLabs\AnsiConverter\AnsiToHtmlConverter; class AnsiToHtmlConverterTest extends \PHPUnit_Framework_TestCase { public function testConvert($expected, $input) { $converter = new AnsiToHtmlConverter(); $this->assertEquals($expected, $converter->convert($input)); } public function getConvertData() { return array( // text is escaped array('<span style="background-color: black; color: white">foo <br /></span>', 'foo <br />'), // newlines are preserved array("<span style=\"background-color: black; color: white\">foo\nbar</span>", "foo\nbar"), // backspaces array('<span style="background-color: black; color: white">foo </span>', "foobar\x08\x08\x08 "),這是一份把ANSI轉換成HTML5的php類別庫,需要的朋友可以下載使用。
<?php header('Content-type: text/plain; charset=UTF-8'); $in = file_get_contents('emoji-data/emoji.json'); $catalog = json_decode($in, true); echo file_get_contents('inc.css'); $max = 0; foreach ($catalog as $item){ $max = max($item['sheet_x'], $max); $max = max($item['sheet_y'], $max); } $fact = 100 / $max; $sheet_size = $max + 1; echo "span.emoji-inner { background-size: {$sheet_size}00%; }\n"; foreach ($catalog as $item){ $unilow = unicode_hex_chars($item['unified']); $pos_x = $item['sheet_x'] * $fact; $pos_y = $item['sheet_y'] * $fact; echo ".emoji$unilow { background-position: {$pos_x}% {$pos_y}% !important; }\n"; } function unicode_hex_chars($str){ $out = ''; $cps = explode('-', $str); foreach ($cps as $cp){這是一份emoji的表情轉換PHP類別庫,需要的朋友可以下載使用