【PHP】找几个例子就能快速复习PHP基础知识

1.基础语法

<html>
<head>
  <title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
    //create short variable names
    $tireqty=$_POST['tireqty'];
    $oilqty=$_POST['oilqty'];
    $sparkqty=$_POST['sparkqty'];
   echo '<p>Order processed at ';
   echo '</p>';
  // echo date('H:i, js F');
   // echo $_POST['tireqty'];
   echo $tireqty. 'tires<br />';
   echo $oilqty. 'bottles of oil<br />';
   echo $sparkqty. 'spark plugs<br />';
   /*echo<<<theEnd
    line 1
    line 2
    line 3
theEnd*/

   // echo phpinfo();
    define('TIREPRICE', 100);
    define('OILPRICE', 10);
    define('SPARKPRICE', 4);

    echo TIREPRICE;
    echo '<br />';
    echo $GLOBALS;
    echo '<br />';

    $totalamount = $tireqty * TIREPRICE
               + $oilqty * OILPRICE
               + $sparkqty * SPARKPRICE;
    echo $totalamount;
    // echo 'Subtotal: $'.number_format($totalamount,2).'<br />';
    echo $a=5;
    $b=&$a;
    $a=7;
    echo '<br />';
    echo 'b的值:'.$b;
    // $c=(57/0);//error
    $c=@(57/0);
    //执行操作符
    /*$out=`dir c`;
    // echo $out;
    echo '<pre>'.$out.'</pre>';*/
    //类型操作符
    class sampleClass{};
    $myObject=new sampleClass();
    if($myObject instanceof sampleClass)
    echo"myObject is an instance of sampleClass";
    //print
    print '<br />为何我比echo慢<br />';
  //可变函数
    $a=56;
    echo gettype($a).'<br/>';
    settype($a,'double');
    echo gettype($a).'<br/>';
    if(!is_int($a))
        echo '$a不是整型数据<br/>';
  $c=floatval($a);
  echo $c.'<br/>';
  /
  echo'isset($tireqty):'.isset($tireqty).'<br/>';
  echo'isset($nothere):'.isset($nothere).'<br/>';
  echo'empty($tireqty):'.empty($tireqty).'<br/>';
  echo'empty($nothere):'.empty($nothere).'<br/>'; 
?>

</body>
</html>

2.文件读取

echo $DOCUMENT_ROOT.'<br />';
     echo __FILE__;
     //echo "$DOCUMENT_ROOT/../orders/orders.txt";
    // open file for appending
    // @ $fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'ab');
    $fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'ab');
    // 文件夹位置  php/www/
    flock($fp, LOCK_EX);
    if (!$fp) {
      echo "<p><strong> Your order could not be processed at this time.
            Please try again later.</strong></p></body></html>";
      exit;
    }
    fwrite($fp, $outputstring, strlen($outputstring));
    flock($fp, LOCK_UN);
    fclose($fp);
    echo "<p>Order written.</p>";

3.数组遍历

<?
/*$prices = array( 'Tires' => 100 );
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;*/
// 表达2
$prices = array('Tires' => 100,'Oil' =>10 );
/*while ($element = each($prices)) {
  echo $element['key'];
  echo " - ";
  echo $element['value'];
  echo "<br />";
}*/
//foreach
/*foreach ($prices as $key => $value) {
    echo $key."-".$value.'<br/>';
}*/
//list
reset($prices);  //将当前元素设置到开始处
while (list($product,$price)=each ($prices)) {
    echo "$product - $price<br/>";
}
?>
<!-- console.log($prices); -->

4.代码重用

<?php
  require('header.php');
?>
  <!-- page content -->
  <p>Welcome to the home of TLA Consulting.
  Please take some time to get to know us.</p>
  <p>We specialize in serving your business needs
  and hope to hear from you soon.</p>
<?php
  require('footer.php');
?>

5.类

<?php
  require("page.inc");
  $homepage = new Page();
  $homepage->content ="<p>Welcome to the home of TLA Consulting.
                       Please take some time to get to know us.</p>
                       <p>We specialize in serving your business needs
                       and hope to hear from you soon.</p>";
  $homepage->Display();
?>
<?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); //$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 } } ?>

6.继承

<?php
  require ("page.inc");
  class ServicesPage extends Page
  {
    private $row2buttons = array(
                           "Re-engineering" => "reengineering.php",
                           "Standards Compliance" => "standards.php",
                           "Buzzword Compliance" => "buzzword.php",
                           "Mission Statements" => "mission.php"
                           );
    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);
      $this -> DisplayMenu($this->row2buttons);
      echo $this->content;
      $this -> DisplayFooter();
      echo "</body>\n</html>\n";
    }
  }
  $services = new ServicesPage();
  $services -> content ="<p>At TLA Consulting, we offer a number
  of services.  Perhaps the productivity of your employees would
  improve if we re-engineered your business. Maybe all your business
  needs is a fresh mission statement, or a new batch of
  buzzwords.</p>";
  $services -> Display();
?>

7.迭代实现

class myClass{
        public $a1="a";
        public $b1="2";
        public $c1="3";
        private $d="abc";
        public $e="abc";
        public function getName(){
            echo "name ";
        }
    }
    $itera=new myClass;
    foreach ($itera as $attr) {
        echo $attr.'<br/>';
    }

8.反射

<?php
require_once("page.inc");
$class = new ReflectionClass("Page");
echo "<pre>".$class."</pre>";
?>

9.异常处理

<?php
try  {
  throw new Exception("A terrible error has occurred", 42);
}
catch (Exception $e) {
  echo "Exception ". $e->getCode(). ": ". $e->getMessage()."<br />".
  " in ". $e->getFile(). " on line ". $e->getLine(). "<br />";
}
?>

自定义异常处理

<?php
class myException extends Exception
{
  function __toString()
  {
       return "<table border=\"1\">
       <tr>
       <td><strong>Exception ".$this->getCode()."
       </strong>: ".$this->getMessage()."<br />"."
       in ".$this->getFile()." on line ".$this->getLine()."
       </td>
       </tr>
       </table><br />";
   }
}
try
{
  throw new myException("A terrible error has occurred", 42);
}
catch (myException $m)
{
   echo $m;
}
?>

10.连接MySQL

10.1 查询

<html>
<head>
  <title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results:</h1>
<?php
  // create short variable names
  $searchtype=$_POST['searchtype'];
  $searchterm=trim($_POST['searchterm']);
  if (!$searchtype || !$searchterm) {
     echo 'You have not entered search details.  Please go back and try again.';
     exit;
  }
  if (!get_magic_quotes_gpc()){  //是否自动完成了引号
    $searchtype = addslashes($searchtype);
    $searchterm = addslashes($searchterm);
  }
     $db = new mysqli('localhost', 'root', '123', 'books');
   // $db = mysql_connect('localhost', 'root', '123', 'books');
   // $db = mysqli_connect("localhost", "root", "123","books");  //mysql_connect本扩展自 PHP 5.5.0 起已废弃,并在将来会被移除
   if(!$db){
     die('Could not connect'.mysql_error());
   }
  if (mysqli_connect_errno()) {
     echo 'Error: Could not connect to database.  Please try again later.';
     exit;
  }
  $query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
  $result = $db->query($query);   //执行查询

  $num_results = $result->num_rows;
  echo "<p>Number of books found: ".$num_results."</p>";
  for ($i=0; $i <$num_results; $i++) {
     $row = $result->fetch_assoc();  //取得行
     echo "<p><strong>".($i+1).". Title: ";
     echo htmlspecialchars(stripslashes($row['title']));
     echo "</strong><br />Author: ";
     echo stripslashes($row['author']);
     echo "<br />ISBN: ";
     echo stripslashes($row['isbn']);
     echo "<br />Price: ";
     echo stripslashes($row['price']);
     echo "</p>";
  }
  $result->free();
  $db->close();
?>
</body>
</html>

10.2 插入数据

<html>
<head>
  <title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<h1>Book-O-Rama Book Entry Results</h1>
<?php // create short variable names $isbn=$_POST['isbn']; $author=$_POST['author']; $title=$_POST['title']; $price=$_POST['price']; if (!$isbn || !$author || !$title || !$price) { echo "You have not entered all the required details.<br />" ."Please go back and try again."; exit; } if (!get_magic_quotes_gpc()) { $isbn = addslashes($isbn); $author = addslashes($author); $title = addslashes($title); $price = doubleval($price); echo $isbn.$author.$title.$price; } $db = new mysqli('localhost', 'root', '123', 'books'); if(!$db){ die('Could not open database'.mysql_error()); } if (mysqli_connect_errno()) { echo "Error: Could not connect to database. Please try again later."; exit; } echo '======================================<br/>'; $query = "insert into books values ('".$isbn."', '".$author."', '".$title."', '".$price."')"; $result = $db->query($query); if ($result) { echo $db->affected_rows." book inserted into database."; } else { echo $db->error."An error has occurred. The item was not added."; //price写为123.40 错误Out of range value for column 'price' at row 1 } $db->close(); ?>
</body>
</html>

积累有用的知识:

/*__FUNCTION__只是返回方法的名字;  __METHOD__返回类的名字和方法的名字。*/
      class Test3{
        public function doit(){
          echo __FUNCTION__;
        }
        public function doitAgain(){
          echo __METHOD__;
        }
      }
      $obj = new Test3();
      $obj->doit();
      echo '<br>';
      $obj->doitAgain();
      echo '<br>';
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值