PHP 的快速介绍

 
2.3 Super Globals
Name    Value
HTTP_REFERER    If the user clicked a link to get the current page, this will contain the URL of the previous page they were at, or it will be empty if the user entered the URL directly.
HTTP_USER_AGENT    The name reported by the visitor's browser
PATH_INFO    Any data passed in the URL after the script name
PHP_SELF    The name of the current script
REQUEST_METHOD    Either GET or POST
QUERY_STRING    Includes everything after the question mark in a GET request
<?php
   if (isset($_SERVER['HTTP_REFERER'])) {
      print "The page you were on previously was {$_SERVER['HTTP_REFERER']}<br />";
   } else {
      print "You didn't click any links to get here<br />";
   }
?>

<a href="refer.php">Click me!</a>
2.4 Execute This
The backtick tells the OS to run a program:
print `ls`;
3 Functions
<?php
   function multiply($num1, $num2) {
      $total = $num1 * $num2;
      return $total;
   }

   $mynum = multiply(5, 10);
?>
3.1 Call By Reference
Use & to pass by reference.
<?php
   function square1($number) {
      return $number * $number;
   }

   $val = square1($val);

   function square2(&$number) {
      $number = $number * $number;
   }

   square2($val);
?>
Or to return by reference:
<?php
   function &square1($number) {
      return $number * $number;
   }

   $val =& square1($val);
?>
3.2 Default Values
Parameters can be given default values:
<?php
   function doFoo($Name = "Paul") {
      return "Foo $Name!\n";
   }

   doFoo();
   doFoo("Paul");
   doFoo("Andrew");
?>
3.3 Multiple Arguments
Extra arguments are ignored, but can be retrieved:
<?php
   function some_func($a, $b) {
      for ($i = 0; $i < func_num_args(); ++$i) {
         $param = func_get_arg($i);
         echo "Received parameter $param.\n";
      }
   }

   function some_other_func($a, $b) {
      $param = func_get_args();
      $param = join(", ", $param);
      echo "Received parameters: $param.\n";
   }

   some_func(1,2,3,4,5,6,7,8);
   some_other_func(1,2,3,4,5,6,7,8);
?>
3.4 Function Scope
The scope of a variable is within the function it is in.
This prints out baz:
<?php
   function foo() {
      $bar = "wombat";
   }

   $bar = "baz";
   foo();
   print $bar;
?>
3.5 Functions are Objects
Functions can be passed as values and then invoked:
<?php
   $func = "sqrt";
   if (is_callable($func)) {
      print $func(49);
   }
?>
4 Arrays
<?php
   $myarray = array("Apples", "Oranges", "Pears");
   $size = count($myarray);
   print_r($myarray);
   print $myarray[0];
?>

   
4.1 Associative Arrays
<?php
   $myarray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears");
   var_dump($myarray);
?>
Prints out:
array(3) {
   ["a"]=>
   string(6) "Apples"
   ["b"]=>
   string(7) "Oranges"
   ["c"]=>
   string(5) "Pears"

Access using $array["a"]
4.2 Array Iteration
<?php
   for ($i = 0; $i < count($array); ++$i) {
      print $array[$i];
   }
?>

<?php
   while (list($var, $val) = each($array)) {
      print "$var is $val\n";
   }


   foreach($array as $val) {
     print $val;
   }

   foreach ($array as $key => $val) {
     print "$key = $val\n";
   }
?>
4.3 Manipulations
<?php
   $toppings1 = array("Pepperoni", "Cheese", "Anchovies", "Tomatoes");
   $toppings2 = array("Ham", "Cheese", "Peppers");
   $inttoppings = array_intersect($toppings1, $toppings2);
   $difftoppings = array_diff($toppings1, $toppings2);
   $bothtoppings = array_merge($toppings1, $toppings2);
   var_dump($inttoppings);
   var_dump($difftoppings);
   var_dump($bothtoppings);
?>

4.4 Filter
<?php
   function endswithy($value) {
      return (substr($value, -1) == 'y');
   }

   $people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
   $withy = array_filter($people, "endswithy");
   var_dump($withy);
?>
4.5 In Array
<?php
   $needle = "Sam";
   $haystack = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
   if (in_array($needle, $haystack)) {
      print "$needle is in the array!\n";
   } else {
      print "$needle is not in the array\n";
   }
?>
4.6 Sorting
ksort sort by keys, asort by values.
<?php
   $capitalcities['England'] = 'London';
   $capitalcities['Wales'] = 'Cardiff';
   $capitalcities['Scotland'] = 'Edinburgh';
   ksort($capitalcities);
   var_dump($capitalcities);
   asort($capitalcities);
   var_dump($capitalcities);
?>
4.7 Serialize
<?php
   $array["a"] = "Foo";
   $array["b"] = "Bar";
   $array["c"] = "Baz";
   $array["d"] = "Wom";

   $str = serialize($array);
   $strenc = urlencode($str);
   print $str . "\n";
   print $strenc . "\n";
?>

<?php
   $arr = unserialize(urldecode($strenc));
   var_dump($arr);
?>
5 Objects
Define and use a class:
<?php
class dog {
   public function bark() {
      print "Woof!\n";
   }
}

class poodle extends dog {
   public function bark() {
      print "Yip!\n";
   }
}

$poppy = new poodle;
$poppy->bark();
?>
5.1 Class Variables
class dog {
   public $Name;

   public function bark() {
      print "Woof!\n";
   }
}

$poppy->Name = "Poppy";

//not this way:
$poppy->$Name = "Poppy";
5.2 This
To set class variables reference them using this.
function bark() {
   print "{$this->Name} says Woof!\n";
}
5.3 Access Control
Public: This variable or function can be used from anywhere in the script
Private: This variable or function can only be used by the object it is part of; it cannot be accessed elsewhere
Protected: This variable or function can only be used by the object it is part of, or descendents of that class
Final: This variable or function cannot be overridden in inherited classes
Abstract: This function or class cannot be used directly - you must inherit from them first
5.4 Constructors and Destructors
class poodle extends dog {
   public function bark() {
      print "Yip!\n";
   }
   
   public function __construct($DogName) {
      parent::__construct($DogName);
      print "Creating a poodle\n";
   }

   public function __destruct() {
     print "{$this->Name} is no more...\n";
     parent::__destruct();
   }
}
5.5 Copying an Object
The clone keyword copies all member variables and then calls __clone.
<?php
   abstract class dog {
      public function __clone() {
         echo "In dog clone\n";
      }
   }

   class poodle extends dog {
      public $Name;

      public function __clone() {
         echo "In poodle clone\n";
         parent::__clone();
      }
   }

   $poppy = new poodle();
   $poppy->Name = "Poppy";

   $rover = clone $poppy;
?>
5.6 Comparisonshttp://www.joyforging.com/
== compares the objects' contents.
=== compares the objects' handles.
5.7 Static Class Variables
Just like Java.
<?php
   class employee {
      static public $NextID = 1;
      public $ID;

      public function __construct() {
         $this->ID = self::$NextID++;
      }
   }

   $bob = new employee;
   $jan = new employee;
   $simon = new employee;

   print $bob->ID . "\n";
   print $jan->ID . "\n";
   print $simon->ID . "\n";
   print employee::$NextID . "\n";
?>
6 Forms
This form:
<form action="someform.php" method="GET">
Name: <input type="text" name="Name" value="Jim" /><br />
Password: <input type="password" name="Password" maxlength="10" /><br />
Age range: <select name="Age">
<option value="Under 16">Under 16</option>
<option value="16-30" SELECTED>16-30</option>
<option value="31-50">31-50</option>
<option value="51-80">51-80</option>
</select><br /><br />
Life story:<br /> <textarea name="Story" rows="10" cols="80">Enter your life story here</textarea><br /><br />
<input type="radio" name="FaveSport" value="Tennis"> Tennis</input>
<input type="radio" name="FaveSport" value="Cricket"> Cricket</input>
<input type="radio" name="FaveSport" value="Baseball"> Baseball</input>
<input type="radio" name="FaveSport" value="Polo"> Polo</input>
<br />
<input type="checkbox" name="Languages[]" value="PHP" CHECKED> PHP</input>
<input type="checkbox" name="Languages[]" value="CPP"> C++</input>
<input type="checkbox" name="Languages[]" value="Delphi"> Delphi</input>
<input type="checkbox" name="Languages[]" value="Java"> Java</input>
<br /><input type="submit" />
</form>
would be handled with:
<?php
   $_GET['Languages'] = implode(', ', $_GET['Languages']);
   $_GET['Story'] = str_replace("\n", "<br />", $_GET['Story']);

   print "Your name: {$_GET['Name']}<br />";
   print "Your password: {$_GET['Password']}<br />";
   print "Your age: {$_GET['Age']}<br /><br />";
   print "Your life story:<br />{$_GET['Story']}<br /><br />";
   print "Your favourite sport: {$_GET['FaveSport']}<br />";
   print "Languages you chose: {$_GET['Languages']}<br />";
?>
7 Cookies
Use setcookie to set and _COOKIE to read.
<?php
   if (!isset($_COOKIE['Ordering'])) {
      setcookie("Ordering", $_POST['ChangeOrdering'], time() + 31536000);
   }
?>

<form method="POST" action="mbprefs.php"> Reorder messages:
<select name="ChangeOrdering">
<option value="DateAdded ASC">Oldest first
<option value="DateAdded DESC">Newest first
<option value="Title ASC">By Title, A-Z
<option value="Title DESC">By Title, Z-A
</select>
<input type="submit" value=" Save Settings ">
</form>
8 Sessions
Like Servlet sessions.
Start one with session_start().
Read and write session data with $_SESSION['var']
End with session_destroy()
9 MySQL
<?php
//Connect to the database
   mysql_connect("localhost", "phpuser", "alm65z");
   mysql_select_db("phpdb");

//Send a query and get resutls
   $result = mysql_query("SELECT * FROM usertable");
   $numrows = mysql_num_rows($result);
   print "There are $numrows people in usertable\n";

//Use a variable in the query, just place it in.
   $result = mysql_query(
      "SELECT ID FROM webpages WHERE Title = '$SearchCriteria';");

//Free memory
   mysql_free_result($result);

//Close connection
   mysql_close();

?>
10 Conclusion
Very popular.
Easy to incrementally add functionality to static pages.
Many Content Management Systems (CMS) use PHP.
许多PHP 库[4]可用:模板、XML 解析器、压缩、数据库等。
网址
维基百科:PHP,http ://en.wikipedia.org/wiki/PHP
实用 PHP 编程,http://hudzilla.org/phpwiki/index.php?title=Main_Page
维基百科:LAMP_%28software_bundle%29,http://www.wikipedia.org/wiki/LAMP_%28software_bundle%29
维基百科:List_of_PHP_libraries, http: //www.wikipedia.org/wiki/List_of_PHP_libraries
此演讲可在http://jmvidal.cse.sc.edu/talks/php/
版权所有 ? 2009 José M. Vidal 。 版权所有。2008 年 2 月 6 日上午 10:45

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值