当前位置:  编程技术>php
本页文章导读:
    ▪PHP常用代码大全(新手入门必备)       1、连接MYSQL数据库代码 <?php $connec=mysql_connect("localhost","root","root") or die("不能连接数据库服务器: ".mysql_error()); mysql_select_db("liuyanben",$connec) or die ("不能选择数据库: ".mysql_error()); mysql_query(".........
    ▪《Head First 设计模式》代码之PHP版(面向对象学习)第1/2页       书中的例子都比较浅显易懂,不过由于是外国佬写的,所以例子的习惯不是很附合中国特色,可能偶尔看起来有些别扭,还有语言习惯也不是中国风。当然��看过这本书之后,你才能深刻.........
    ▪PHP print类函数使用总结       代码如下:<?php /*************by garcon1986*********/ //print和echo的区别: //1. echo可以输入多个字符串,而print不能。 print "hello"."world"; //成功 echo "hello"."world"; //成功 //print "hello","world"; //失败 echo "he.........

[1]PHP常用代码大全(新手入门必备)
    来源: 互联网  发布时间: 2013-11-30
1、连接MYSQL数据库代码
<?php
$connec=mysql_connect("localhost","root","root") or die("不能连接数据库服务器: ".mysql_error());
mysql_select_db("liuyanben",$connec) or die ("不能选择数据库: ".mysql_error());
mysql_query("set names 'gbk'");
?>

2、读取数据库,并实现循环输出
<?php
$sql="select * from liuyan order by ly_id desc";
$conn=mysql_query($sql,$connec);
while($rs=mysql_fetch_array($conn)){
?>
循环的内容.........
<?php
}
?>

3、如何实现分页,包括两个函数,两个调用
1)两个函数
<?
//分页函数
function genpage(&$sql,$page_size=2)
{
global $prepage,$nextpage,$pages,$sums; //out param
$page = $_GET["page"];
$eachpage = $page_size;
$pagesql = strstr($sql," from ");
$pagesql = "select count(*) as ids ".$pagesql;
$conn = mysql_query($pagesql) or die(mysql_error());
if($rs = mysql_fetch_array($conn)) $sums = $rs[0];
$pages = ceil(($sums-0.5)/$eachpage)-1;
$pages = $pages>=0?$pages:0;
$prepage = ($page>0)?$page-1:0;
$nextpage = ($page<$pages)?$page+1:$pages;
$startpos = $page*$eachpage;
$sql .=" limit $startpos,$eachpage ";
}
// 显示分页
function showpage()
{
global $page,$pages,$prepage,$nextpage,$queryString; //param from genpage function
$shownum =10/2;
$startpage = ($page>=$shownum)?$page-$shownum:0;
$endpage = ($page+$shownum<=$pages)?$page+$shownum:$pages;

echo "共".($pages+1)."页: ";
if($page>0)echo "<a href=/blog_article/$PHP_SELF/page/0$queryString/gt;首页/lt;/a/gt;.html";
if($startpage>0)
echo " ... <b><a href=/blog_article/$PHP_SELF/page/.html".($page-$shownum*2)."$queryString>?</a></b>";
for($i=$startpage;$i<=$endpage;$i++)
{
if($i==$page) echo " <b>[".($i+1)."]</b> ";
else echo " <a href=/blog_article/$PHP_SELF/page/.html$i$queryString>".($i+1)."</a> ";
}
if($endpage<$pages)
echo "<b><a href=/blog_article/$PHP_SELF/page/.html".($page+$shownum*2)."$queryString>?</a></b> ... ";
if($page<$pages)
echo "<a href=/blog_article/$PHP_SELF/page/.html$pages$queryString>尾页</a>";
}
//显示带分类的分页
function showpage1()
{
$fenlei=$_GET["fenleiid"];
global $page,$pages,$prepage,$nextpage,$queryString; //param from genpage function
$shownum =10/2;
$startpage = ($page>=$shownum)?$page-$shownum:0;
$endpage = ($page+$shownum<=$pages)?$page+$shownum:$pages;

echo "共".($pages+1)."页: ";
if($page>0)echo "<a href=/blog_article/$PHP_SELF/fenleiid/$fenlei/amp;page/0$queryString/gt;首页/lt;/a/gt;.html";
if($startpage>0)
echo " ... <b><a href=/blog_article/$PHP_SELF/fenleiid/$fenlei/amp;page/.html".($page-$shownum*2)."$queryString>?</a></b>";
for($i=$startpage;$i<=$endpage;$i++)
{
if($i==$page) echo " <b>[".($i+1)."]</b> ";
else echo " <a href=/blog_article/$PHP_SELF/fenleiid/$fenlei/amp;page/.html$i$queryString>".($i+1)."</a> ";
}
if($endpage<$pages)
echo "<b><a href=/blog_article/$PHP_SELF/fenleiid/$fenlei/amp;page/.html".($page+$shownum*2)."$queryString>?</a></b> ... ";
if($page<$pages)
echo "<a href=/blog_article/$PHP_SELF/fenleiid/$fenlei/amp;page/.html$pages$queryString>尾页</a& amp; gt;";
}
?>
2)两个调用
第一个
<?php
$sql="select * from liuyan order by ly_id desc";
genpage($sql); //只需要正常代码加上这一行就ok。
$conn=mysql_query($sql,$connec);
while($rs=mysql_fetch_array($conn)){
?>
第二个
<?php
}
?>
<?php
showpage(); //显示页
?>
<?php
mysql_close();
?>

4、服务器端包含
<?php require_once('conn.php'); ?>

5、如何将一条记录写入数据库,然后提示并跳转页面
<?php
$ly_title=$_POST["ly_title"];
$ly_content=$_POST["ly_content"];
$ly_time=$_POST["ly_time"];
$ly_author=$_POST["ly_author"];
$ly_email=$_POST["ly_email"];
$sql="insert into liuyan(ly_title,ly_content,ly_time,ly_author,ly_email) values('".$ly_title."','".$ly_content."','".$ly_time."','".$ly_author."','".$ly_email."')";
mysql_query($sql,$connec);
echo("<script type='text/javascript'> alert('添加成功!');location.href='/blog_article/index.html';</script>");
?>

6、 弹出对话框,并发生页面跳转
<?php
echo("<script type='text/javascript'> alert('添加成功!');location.href='/blog_article/index.html';</script>");
?>

7、 信息查看页面(有条件读取数据库)
1)有条件读取数据库
<?php
$sql="select * from liuyan where ly_id=$_GET[id]";
$conn=mysql_query($sql,$connec);
$rs=mysql_fetch_array($conn);
?>
2) 将某个字段输出
<?=$rs[ly_title]?>
3)关闭数据库
<?php
mysql_close();
?>

8、对数据库中某一条记录进行更新操作,并作提示跳转
<?php
$ly_title=$_POST["ly_title"];
$ly_content=$_POST["ly_content"];
$ly_time=$_POST["ly_time"];
$ly_author=$_POST["ly_author"];
$ly_email=$_POST["ly_email"];
$sql="update liuyan set ly_title='$ly_title',ly_content='$ly_content',ly_time='$ly_time',ly_author='$ly_author',ly_email='$ly_email' where ly_id=$_GET[id]";
mysql_query($sql,$connec);
echo("<script type='text/javascript'> alert('更新成功!');location.href='/index.html';</script>");
?>

9、 如何删除数据库中的一条记录
<?php
$sql="delete from liuyan where ly_id=$_GET[id]";
mysql_query($sql,$connec);
echo("<script type='text/javascript'> alert('删除成功!');location.href='/index.html';</script>");
?>

10、 如何进行会员登录验证
<?php
session_start();
$username=$_POST["username"];
$password=$_POST["password"];
$sql="select * from admin where username='".$username."' && password='".$password."'";
$result=mysql_query($sql,$connec);
if($row=mysql_fetch_array($result)){
session_register("admin");
$admin=$username;
echo("<script type='text/javascript'> alert('登录成功!');location.href='/blog_article/admin.html';</script>");}
else
{
echo("<script type='text/javascript'> alert('你输入的用户名或密码错误,请重新输入!');location.href='/blog_article/login.html';</script& gt;");
}
mysql_close();
?>

11、如何对SESSION进行检验(后台检查页面的制作)
<?php
session_start();
if(!isset($_SESSION["admin"])){
header("location:login.php");
exit;
}
?>

12、 验证用户名及密码是否填写(javascript)
<SCRIPT language=javascript>
<!--
function confirmlogin()
{
if (document.frmmain.username.value.length<4 || document.frmmain.username.value=="")
{
document.frmmain.username.focus();
document.frmmain.username.select;
window.alert("请输入你的用户名!");
return false;
}
if (document.frmmain.password.value.length<4)
{
document.frmmain.password.focus();
document.frmmain.password.select;
window.alert("请输入你的密码!");
return false;
}
return true;
}
//-->
</SCRIPT>

13、 在PHP中调用编辑器的方法
1)将编辑器文件夹放置后台管理文件夹内。
2)利用以下语句进行引入操作。
<input name="content" type="hidden" value=''>
<IFRAME ID="eWebEditor1" src="/blog_article/eWebEditorPHP38/ewebeditor/id/content/amp; frameborder/.htm"0" scrolling="no" width="550" height="350"></IFRAME>
注:eWebEditorPHP38编辑器文件夹的名称。
id=content中content为上面隐藏域的名称

14、循环输出(能够实现分列)
1)首先插入一行一列表格
<?php
$i=1;
?>
<table>
<tr>
<?php
while($rs=mysql_fetch_array($conn)){
?>
<td>
被循环的其它表格和输出
</td>
<?php
if ($i % 2==0) {
echo "</tr><tr>";
}
$i++;
}
?>
</tr>
</table>

15、 给下拉列表框绑定数据(并且在修改时默认选中)
<select name="fenleiid">
<?php
$sql="select * from fenleibiao";
$conn=mysql_query($sql,$connec);
while($rs1=mysql_fetch_array($conn)){
?>
<option value="<?=$rs1["fenleiid"]?>"
<?
if ($rs["fenleiid"]==$rs1["fenleiid"]){
echo "selected" ;
}
?>>
<?=$rs1["flname"]?>
</option>
<?php>
}
?>
</select>

16、获取字符长度函数
strlen($c)>12

17、 定义一个字符截取函数
用法:<?=substrgb($rs["title"],10)?>
function substrgb($in,$num){
$pos=0;
$out="";
while($c=substr($in,$pos,1)){
if($c=="\n") break;
if(ord($c)>128){
$out.=$c;
$pos++;
$c=substr($in,$pos,1);

$out.=$c;
}else{
$out.=$c;
}
$pos++;
if($pos>=$num) break;
}
if($out!=$in) $out = $out . "...";
return $out;
}

18、判断是否是数字
!is_numeric(qq)

19、PHP技术中获取当前日期
$ptime=date("y-m-d");

20、用户注册时所使用的PHP验证程序
if ($admin=="" or (strlen($admin)>16) or (strlen($admin)<2)) {
echo "<SCRIPT language=JavaScript>alert('请输入用户名(不能大于16小于2)');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($password=="" or strlen($password)>16 or strlen($password)<6) {
echo "<SCRIPT language=JavaScript>alert('密码长度为6-16个字符');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($password=="") {
echo "<SCRIPT language=JavaScript>alert('确认密码不能为空');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}else{
if ($password!=$password1) {
echo "<SCRIPT language=JavaScript>alert('密码和确认密码不一致');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
}
if ($wt="") {
echo "<SCRIPT language=JavaScript>alert('密码问题不能为空');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($da="") {
echo "<SCRIPT language=JavaScript>alert('问题答案不能为空');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";

}
if ($qq!="") {
if (!is_numeric($qq)) {
echo "<SCRIPT language=JavaScript>alert('QQ号码必须是数字');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
}
if ($youbian=="" or strlen($youbian)!=6) {
echo "<SCRIPT language=JavaScript>alert('请正确输入邮编');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($youbian!="") {
if (!is_numeric($youbian)) {
echo "<SCRIPT language=JavaScript>alert('邮编必须是数字');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
}
if ($dizhi="") {
echo "<SCRIPT language=JavaScript>alert('住址不能为空');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($mail=="") {
echo "<SCRIPT language=JavaScript>alert('E-mail不能为空!');";
echo "this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($textarea=="") {
echo "<SCRIPT language=JavaScript>alert('个人说明不能为空!');";
echo "this.location.href='vbscript:history.back()';</SCRIPT>";
}
if ($textarea=="" or strlen(textarea)>150) {
echo "<SCRIPT language=JavaScript>alert('个人说明为150个字符');";
echo"this.location.href='vbscript:history.back()';</SCRIPT>";
}

24、对输出的内容进行判断,从而输出其它结果
<?php
if ($rs["active"]==1) {
echo "<font color='#ff0000'>激活</font>";
}else{
echo "禁用";
}
?>

25.字符截取函数
<?=substr("$rs[zixun_biaoti]",0,28)?>

26.男女问题或单选带选择的
<input type="radio" name="hy_zhuangtai" value="男" <?php if ($rs["hy_zhungtai"]==="男") { echo "checked";}?>>男
<input type="radio" name="hy_zhuangtai" value="女" <?php if ($rs["hy_zhuangtai"]==="女") { echo "checked";}?>>女

27.单选不带单选框的
<?php if ($rs['hy_zhuangtai']=='锁定'){?>
<a href="/blog_article/Userzt/action/yes/amp;id/lt;php echo $rs[.html'hy_id'];?>">锁定</a>
<?php }
else{?>
<a href="/blog_article/Userzt/id/lt;php echo $rs[.html'hy_id'];?>&action=no">解锁</a>
<?php }?>
它的 save页是
<?php require_once('http://www.cnblogs.com/conn.php'); ?>
<?php
$hy_id=$_GET['id'];
$action=$_GET['action'];
if ($action=='yes'){
$sql="update hybiao set hy_zhuangtai='锁定' where hy_id='$id'";
$query=mysql_query($sql,$connec);
echo("<script type='text/javascript'>location.href='/blog_article/UserManage.html';</script>");
}
else{
$sql="update hybiao set hy_zhuangtai='正常' where hy_id='$id'";
$query=mysql_query($sql,$connec);
echo("<script type='text/javascript'>location.href='/blog_article/UserManage.html';</script>");
}
mysql_close();
?>

28. 如果文字过长,则将过长的部分变成省略号显示
<DIV >
<NOBR> 就是比如有一行文字,很长,表格内一行显示不下.</NOBR>
</DIV>

29.
禁止复制,鼠标拖动选取
<body ondragstart=window.event.returnValue=false oncontextmenu=window.event.returnValue=false onselectstart=event.returnValue=false>
30.大 中 小 文字的变化
<script type="text/javascript">
function doZoom(size)
{document.getElementById('zoom').style.fontSize=size+'px';}
</script>
<span id="zoom">需要指定大小的文字</span>
<a href="javascript:doZoom(16)">大</a> <a href="javascript:doZoom(14)">中</a> <a href="javascript:doZoom(12)">小</a>

30.添加到收藏夹和设为首页
<a href=# onclick="this.style.behavior='url(#default#homepage)'; this.setHomePage('http://www.makewing.com/lanren/');">设为首页</a>
<a href="javascript:window.external.AddFavorite('http://www.makewing.com /lanren/','懒人图库')">收藏本站</a>

31.记录并显示网页的最后修改时间
<script language=JavaScript>
document.write("最后更新时间: " + document.lastModified + "")
</script>

32.节日倒计时
<Script Language="JavaScript">
   var timedate= new Date("October 1,2002");
   var times= "国庆节";
   var now = new Date();
   var date = timedate.getTime() - now.getTime();
   var time = Math.floor(date / (1000 * 60 * 60 * 24));
   if (time >= 0)
   document.write( "现在离"+times+"还有: "+time +"天")
</Script>

33.打开窗口即最大化
<script language="JavaScript">
<!-- Begin
self.moveTo(0,0)
self.resizeTo(screen.availWidth,screen.availHeight)
// End -->
</script>

34.加入背景音乐
<bgsound src="/blog_article/mid/windblue[1].mid" loop="-1"> 只适用于IE
<embed src="/blog_article/music.mid" autostart="true" loop="true" hidden="true"> 对Netscape ,IE 都适用

35.滚动
<marquee direction=up height=146 onmouseout=start() onmouseover=stop() scrollAmount=2>
滚动信息
</marquee>

36.防止点击空链接时,页面往往重置到页首端
代码“javascript:void(null)”代替原来的“#”标记

37.不能点右键,不用CTRL+A,不能复制作!
<body oncontextmenu="window.event.returnValue=false"
onkeypress="window.event.returnValue=false"
onkeydown="window.event.returnValue=false"
onkeyup="window.event.returnValue=false"
ondragstart="window.event.returnValue=false"
onselectstart="event.returnValue=false">
</body>

37.随机变换背景图象(一个可以刷新心情的特效)
<Script Language="JavaScript">
   image = new Array(4); //定义image为图片数量的数组
   image [0] = 'tu0.gif' //背景图象的路径
   image [1] = 'tu1.gif'
   image [2] = 'tu2.gif'
   image [3] = 'tu3.gif'
   image [4] = 'tu4.gif'
   number = Math.floor(Math.random() * image.length);
   document.write("<BODY BACKGROUND="+image[number]+">");
</Script>

38.划过链接 手型鼠标


39.如何关闭层
<div id="Layer1"></div>
<a href="#" onClick="Layer1.style.display='none'">关闭层</a>

40.<a href=javascript:close()>[关闭窗口]</a>

41.凹陷文字背景为灰色
<div >
<font disabled>
怎么样,我凹下去了吧?<br>
你不想试试吗?<br>
<a href="www.lenvo.cnhttp://www.lenvo.cn/">www.lenvo.cn</a></font>
</div>

42.给表格做链接
<table width="100%" onclick="window.open('http://www.makewing.com/', '_blank')" >
<tr>
<td height="100" bgcolor="f4f4f4"> </td>
</tr>
</table>

43.后退&关闭窗口
后退:javascript:history.back(1)
关闭:javascript:window.close();

44.如果文字过长,则将过长的部分变成省略号显示
<DIV >
<NOBR>就是比如有一行文字,很长,表格内一行显示不下.</NOBR>
</DIV>

45.禁止复制,鼠标拖动选取
<body ondragstart=window.event.returnValue=false oncontextmenu=window.event.returnValue=false onselectstart=event.returnValue=false>

    
[2]《Head First 设计模式》代码之PHP版(面向对象学习)第1/2页
    来源: 互联网  发布时间: 2013-11-30
书中的例子都比较浅显易懂,不过由于是外国佬写的,所以例子的习惯不是很附合中国特色,可能偶尔看起来有些别扭,还有语言习惯也不是中国风。当然��看过这本书之后,你才能深刻理解设计模式到底能为你解决哪些问题,不能为你解决哪些问题(比如不能代替你的编码)。
  我将书中部分代码改成PHP,看下代码再配合概念应该是比较容易理解了。

策略模式
代码如下:

<?php
/**
* 策略模式
* 定义了算法族,分别封装起来,让它们之间可以互相替换,
* 此模式让算法的变化独立于使用算法的客户。
*/
//飞行行为接口
interface FlyBehavior {
public function fly();
}
//呱呱叫行为接口
interface QuackBehavior {
public function quack();
}
//翅膀飞行
class FlyWithWings implements FlyBehavior {
public function fly() {
echo "I'm flying!!\n";
}
}
//不会飞
class FlyNoWay implements FlyBehavior {
public function fly() {
echo "I can't fly!\n";
}
}
class FlyRocketPowered implements FlyBehavior {
public function fly() {
echo "I'm flying with a rocket!\n";
}
}
class Qquack implements QuackBehavior {
public function quack() {
echo "Quack\n";
}
}
class Squeak implements QuackBehavior {
public function quack() {
echo "Squeak\n";
}
}
class MuteQuack implements QuackBehavior {
public function quack() {
echo "<< Silence >>\n";
}
}
abstract class Duck {
protected $quack_obj;
protected $fly_obj;
public abstract function display();

public function performQuack() {
$this->quack_obj->quack();
}
public function performFly() {
$this->fly_obj->fly();
}
public function swim() {
echo "All ducks float, even decoys!\n";
}
public function setFlyBehavior(FlyBehavior $fb) {
$this->fly_obj = $fb;
}
public function setQuackBehavior(QuackBehavior $qb) {
$this->quack_obj = $qb;
}
}

class ModelDuck extends Duck {
public function __construct() {
$this->fly_obj = new FlyNoWay();
$this->quack_obj = new MuteQuack();
}
public function display() {
echo "I'm a model duck!\n";
}
}

$model = new ModelDuck();
$model->performFly();
$model->performQuack();
//提供新的能力
$model->setFlyBehavior(new FlyRocketPowered());
$model->setQuackBehavior(new Squeak());
$model->performFly();
$model->performQuack();

?>

单件模式
代码如下:

<?php
/**
* 单件模式
* 确保一个类只有一个实例,并提供一个全局访问点。
*/
class MyClass {
private static $uniqueInstance;
private function __construct() {

}
public static function getInstance() {
if (self::$uniqueInstance == null) {
self::$uniqueInstance = new MyClass();
}
return self::$uniqueInstance;
}
}
$myClass = MyClass::getInstance();
var_dump($myClass);
$myClass = MyClass::getInstance();
var_dump($myClass);
?>

工厂方法模式
代码如下:

<?php
abstract class PizzaStore {
public function orderPizza($type) {
$pizza = $this->createPizza($type);

$pizza->prepare();
$pizza->bake();
$pizza->cut();
$pizza->box();
return $pizza;
}

public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
public function createPizza($type) {
if ($type == "cheese") {
return new NYStyleCheesePizza();
} elseif ($type == "veggie") {
return new NYStyleVeggiePizza();
} elseif ($type == "clam") {
return new NYStyleClamPizza();
} elseif ($type == "papperoni") {
return new NYStylePapperoniPizza();
} else {
return null;

}
}
}
class ChicagoPizzaStore extends PizzaStore {
public function createPizza($type) {
if ($type == "cheese") {
return new ChicagoStyleCheesePizza();
} elseif ($type == "veggie") {
return new ChicagoStyleVeggiePizza();
} elseif ($type == "clam") {
return new ChicagoStyleClamPizza();
} elseif ($type == "papperoni") {
return new ChicagoStylePapperoniPizza();
} else {
return null;
}
}
}
abstract class Pizza {
public $name;
public $dough;
public $sauce;
public $toppings = array();

public function prepare() {
echo "Preparing " . $this->name . "\n";
echo "Yossing dough...\n";
echo "Adding sauce...\n";
echo "Adding toppings: \n";
for ($i = 0; $i < count($this->toppings); $i++) {
echo " " . $this->toppings[$i] . "\n";
}
}

public function bake() {
echo "Bake for 25 minutes at 350\n";
}

public function cut() {
echo "Cutting the pizza into diagonal slices\n";
}

public function box() {
echo "Place pizza in official PizzaStore box\n";
}

public function getName() {
return $this->name;
}
}

class NYStyleCheesePizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and cheese Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano Cheese";
}
}

class NYStyleVeggiePizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and veggie Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano veggie";
}
}
class NYStyleClamPizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and clam Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano clam";
}
}
class NYStylePapperoniPizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and papperoni Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano papperoni";
}
}

class ChicagoStyleCheesePizza extends Pizza {
public function __construct() {
$this->name = "Chicago Style Deep Dish Cheese Pizza";
$this->dough = "Extra Thick Crust Dough";
$this->sauce = "Plum Tomato Sauce";

$this->toppings[] = "Shredded Mozzarella Cheese";
}

public function cut() {
echo "Cutting the pizza into square slices\n";
}
}

$myStore = new NYPizzaStore();
$chicagoStore = new ChicagoPizzaStore();
$pizza = $myStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

$pizza = $chicagoStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

?>

工厂模式
代码如下:

<?php
abstract class PizzaStore {
public function orderPizza($type) {
$pizza = $this->createPizza($type);

$pizza->prepare();
$pizza->bake();
$pizza->cut();
$pizza->box();
return $pizza;
}

public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
public function createPizza($type) {
$pizza = null;
$ingredientFactory = new NYPizzaIngredientFactory();
if ($type == "cheese") {
$pizza = new CheesePizza($ingredientFactory);
$pizza->setName('New York Style Cheese Pizza');
} elseif ($type == "veggie") {
$pizza = new VeggiePizza($ingredientFactory);
$pizza->setName('New York Style Veggie Pizza');
} elseif ($type == "clam") {
$pizza = new ClamPizza($ingredientFactory);
$pizza->setName('New York Style Clam Pizza');
} elseif ($type == "papperoni") {
$pizza = new PapperoniPizza($ingredientFactory);
$pizza->setName('New York Style Papperoni Pizza');
}
return $pizza;
}
}
class ChicagoPizzaStore extends PizzaStore {
public function createPizza($type) {
if ($type == "cheese") {
return new ChicagoStyleCheesePizza();
} elseif ($type == "veggie") {
return new ChicagoStyleVeggiePizza();
} elseif ($type == "clam") {
return new ChicagoStyleClamPizza();
} elseif ($type == "papperoni") {
return new ChicagoStylePapperoniPizza();
} else {
return null;
}
}
}
interface PizzaIngredientFactory {
public function createDough();
public function createSauce();
public function createCheese();
public function createVeggies();
public function createPepperoni();
public function createClam();
}
class NYPizzaIngredientFactory implements PizzaIngredientFactory {
public function createDough() {
return new ThinCrustDough();
}
public function createSauce() {
return new MarinaraSauce();
}
public function createCheese() {
return new ReggianoCheese();
}
public function createVeggies() {
$veggies = array(
new Garlic(),
new Onion(),
new Mushroom(),
new RedPepper(),
);
return $veggies;
}
public function createPepperoni() {
return new SlicedPepperoni();
}
public function createClam() {
return new FreshClams();
}
}
class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory {
public function createDough() {
return new ThickCrustDough();
}
public function createSauce() {
return new PlumTomatoSauce();
}
public function createCheese() {
return new Mozzarella();
}
public function createVeggies() {
$veggies = array(
new BlackOlives(),
new Spinach(),
new EggPlant(),
);
return $veggies;
}
public function createPepperoni() {
return new SlicedPepperoni();
}
public function createClam() {
return new FrozenClams();
}
}
abstract class Pizza {
public $name;
public $dough;
public $sauce;
public $veggies = array();
public $cheese;
public $pepperoni;
public $clam;

public abstract function prepare();

public function bake() {
echo "Bake for 25 minutes at 350\n";
}

public function cut() {
echo "Cutting the pizza into diagonal slices\n";
}

public function box() {
echo "Place pizza in official PizzaStore box\n";
}

public function getName() {
return $this->name;
}

public function setName($name) {
$this->name = $name;
}

public function __toString() {

}
}

class CheesePizza extends Pizza {
public $ingredientFactory;

public function __construct(PizzaIngredientFactory $ingredientFactory) {
$this->ingredientFactory = $ingredientFactory;
}

public function prepare() {
echo "Preparing " . $this->name . "\n";
$this->dough = $this->ingredientFactory->createDough();
$this->sauce = $this->ingredientFactory->createSauce();
$this->cheese = $this->ingredientFactory->createCheese();
}
}

class ClamPizza extends Pizza {
public $ingredientFactory;

public function __construct(PizzaIngredientFactory $ingredientFactory) {
$this->ingredientFactory = $ingredientFactory;
}

public function prepare() {
echo "Preparing " . $this->name . "\n";
$this->dough = $this->ingredientFactory->createDough();
$this->sauce = $this->ingredientFactory->createSauce();
$this->cheese = $this->ingredientFactory->createCheese();
$clam = $this->ingredientFactory->createClam();
}
}

$nyPizzaStore = new NYPizzaStore();
$nyPizzaStore->orderPizza('cheese');
?>



    
[3]PHP print类函数使用总结
    来源: 互联网  发布时间: 2013-11-30
代码如下:

<?php
/*************by garcon1986*********/
//print和echo的区别:
//1. echo可以输入多个字符串,而print不能。
print "hello"."world"; //成功
echo "hello"."world"; //成功
//print "hello","world"; //失败
echo "hello","world"; //成功
//2. echo比print更快。
$stime = microtime(true);
print "hello"."world";
$etime = microtime(true);
$total = $etime - $stime;
echo $total.'<br/>';
//microtime — Return current Unix timestamp with microseconds
$stime2 = microtime(true);
echo "hello"."world";
$etime2 = microtime(true);
$total2 = $etime2 - $stime2;
echo $total2.'<br/>';
//执行结果:
//helloworld0.0014331340789795
//helloworld0.00018310546875
//看到echo比print更快。
//print_r — Prints human-readable information about a variable 或数组
$a = "sajfd sfjal sfjalwureoi weu sj we fk io ";
print_r($a);
echo '<br />';
$a = array("b","c","d");
print_r($a);
echo '<br />';
//var_dump — Dumps information about a variable 或数组
//var_dump -- 打印变量的相关信息
$a = "sajfd sfjal sfjalwureoi weu sj we fk io ";
var_dump($a);
echo '<br />';
$a = array("b","c","d");
var_dump($a);
echo '<br />';
var_dump(array("b","c","d"));
echo '<br />';
?>
<?php
/************by garcon1986********/
//%% - 返回百分比符号
//%b - 二进制数
//%c - 依照 ASCII 值的字符
//%d - 带符号十进制数
//%e - 可续计数法(比如 1.5e+3)
//%f - 浮点数(local settings aware)
//%F - 浮点数(not local settings aware)
//%o - 八进制数
//%s - 字符串
//%u - 无符号十进制数
//%x - 十六进制数(小写字母)
//%X - 十六进制数(大写字母)
//printf()函数输出格式化的字符串
$str = "hello";
$number = 456;
//example1
printf("%s world. Day number %s", $str, $number); //输出: hello world. Day number 456
print "<br/>";
//example2
printf("%%", $number); //%
print "<br/>";
printf("%b", $number); //111001000
print "<br/>";
printf("%c", $number); //ascii码
print "<br/>";
printf("%d", $number); //456
print "<br/>";
printf("%e", $number); //4.560000e+2
print "<br/>";
printf("%f", $number); //456.000000
print "<br/>";
printf("%F", $number); //456.000000
print "<br/>";
printf("%o", $number); //710
print "<br/>";
printf("%s", $number); //456
print "<br/>";
printf("%u", $number); //456
print "<br/>";
printf("%x", $number); //1c8
print "<br/>";
printf("%X", $number); //1C8
print "<br/>";
printf("With 2 decimals: %1\$.2f<br />With no decimals: %1\$u<br />",$number);
//With 2 decimals: 456.00
//With no decimals: 456
printf("With 2 decimals: %f<br />With no decimals: %1\$u<br />",$number);
//With 2 decimals: 456.000000
//With no decimals: 456
//fprintf() 函数把格式化的字符串写到指定的输出流(例如:文件或数据库)。
$file = fopen("text.txt","w");
echo fprintf($file, "fprintf 1: %s world. Day number %u", $str, $number).'<br/>'; //38
echo fprintf($file, "fprintf 2: %f", $number).'<br/>'; //21
echo fprintf($file,"fprintf 3: With 2 decimals: %1\$.2f\nWith no decimals: %1\$u",$number).'<br />'; //56
//vprintf()函数输出格式化的字符串。
//vprintf() 中的 arg 参数位于数组中。数组的元素会被插入主字符串的百分比 (%) 符号处。该函数是逐步执行的。在第一个 % 符号中,插入 arg1,在第二个 % 符号处,插入 arg2,依此类推。
vprintf("vprintf: %s world. Day number %u", array($str,$number)); //vprintf: hello world. Day number 456
echo '<br />';
//sprintf() 函数把格式化的字符串写写入一个变量中。
$txt = sprintf("sprintf: %s world. Day number %u",$str,$number);
echo $txt.'<br />'; //sprintf: hello world. Day number 456
//vfprintf() Operates as fprintf() but accepts an array of arguments, rather than a variable number of arguments.
echo vfprintf($file, "vfprintf: %s world! Day number %u", array($str, $number)).'<br />'; //37
//vsprintf() Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.
$txt = vsprintf("vsprintf: %s world. Day number %u",array($str,$number));
echo $txt.'<br />'; //vsprintf: hello world. Day number 456
?>

    
最新技术文章:
▪PHP函数microtime()时间戳的定义与用法
▪PHP单一入口之apache配置内容
▪PHP数组排序方法总结(收藏)
▪php数组排序方法大全(脚本学堂整理奉献)
▪php数组排序的几个函数(附实例)
▪php二维数组排序(实例)
▪php根据键值对二维数组排序的小例子
▪php验证码(附截图)
▪php数组长度的获取方法(三个实例)
▪php获取数组长度的方法举例
▪判断php数组维度(php数组长度)的方法
▪php获取图片的exif信息的示例代码
▪PHP 数组key长度对性能的影响实例分析
▪php函数指定默认值的方法示例
▪php提交表单到当前页面、提交表单后页面重定...
▪php四舍五入的三种实现方法
▪php获得数组长度(元素个数)的方法
▪php日期函数的简单示例代码
▪php数学函数的简单示例代码
▪php字符串函数的简单示例代码
▪php文件下载代码(多浏览器兼容、支持中文文...
▪php实现文件下载、支持中文文件名的示例代码...
▪php文件下载(防止中文文件名乱码)的示例代码
▪解决PHP文件下载时中文文件名乱码的问题
▪php数组去重(一维、二维数组去重)的简单示例
▪php小数点后取两位的三种实现方法
▪php Redis 队列服务的简单示例
▪PHP导出excel时数字变为科学计数的解决方法
▪PHP数组根据值获取Key的简单示例
▪php数组去重的函数代码示例
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3