- PHP stands for PHP: Hypertext Preprocessor
- PHP files can contain text, HTML, JavaScript code, and PHP code
- PHP code is executed on the server, and the result is returned to the browser as plain HTML
- The default file extension for PHP files is ".php"
What can PHP do?
- PHP can generate dynamic page content
- PHP can create, open, read, write, and close files on the server
- PHP can collect form data
- PHP can send and receive cookies
- PHP can add, delete, and modify data in your database
- PHP can restrict users from accessing some pages on your website
- PHP can encrypt data
Installation
If your server does not support PHP, you must:
- Install a web server
- Install PHP
- Install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP:http://php.net/manual/en/install.php
Recommended integrated development environment: WAMPhttp://www.wampserver.com/
PHP Basic Syntax
PHP scripts can be placed anywhere in a document.
PHP scripts start with <?php and end with ?>:
<!DOCTYPE html> <html> <body> <h1>我的第一个 PHP 页面</h1> <?php echo "Hello World!"; // 这是一行注释 /* 这是 多行 注释 */ ?> </body> </html>
Every code line in PHP must end with a semicolon
Two basic instructions for outputting text in the browser: echo and print.
PHP Variables
Variables start with the $ symbol, followed by the variable name
PHP has no command for declaring variables.
A variable is created when you first assign a value to it:
PHP is a weakly typed language
PHP automatically converts the variable to the correct data type based on its value.
In strongly typed programming languages, we must declare (define) the type and name of a variable before using it.
PHP Variable Scope
PHP has four different variable scopes:
- local
- global
- static
- parameter
Local and global scope
Variables defined outside all functions have global scope. Global variables can be accessed by any part of the script except functions. To access a global variable inside a function, you need to use the global keyword.
Variables declared inside a PHP function are local variables and can only be accessed inside the function:
<?php
$x=5; // 全局变量
function myTest()
{
$y=10; // 局部变量
echo "<p>测试变量在函数内部:<p>";
echo "变量 x 为: $x";
echo "<br>";
echo "变量 y 为: $y";
}
myTest();
echo "<p>测试变量在函数外部:<p>";
echo "变量 x 为: $x";
echo "<br>";
echo "变量 y 为: $y";
?>
To access a global variable defined outside a function from within a function, we need to prepend the global keyword to the variable inside the function:
<?php
$x=5;
$y=10;
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // 输出 15
?>
PHP stores all global variables in an array named $GLOBALS[index]. The index holds the name of the variable. This array can be accessed inside functions and can also be used directly to update global variables.
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
Static Scope
When a function completes, all of its variables are usually deleted. However, sometimes you want a local variable not to be deleted; you can usestatickeyword
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Parameter Scope
Parameters are local variables that receive values passed to the function by the calling code.
Parameters are declared in the parameter list, as part of the function declaration:
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
PHP echo and print statements
- echo - can output one or more strings
- print - only allows outputting one string, and its return value is always 1
Tip: echo outputs faster than print, echo has no return value, and print has a return value of 1.
Both echo and print are language constructs. When using them, you can omit the parentheses or add parentheses: echo or echo(), print or print().
<?php echo "<h2>PHP is fun!</h2>"; echo "Hello world!<br>"; echo "I'm about to learn PHP!<br>"; echo "This", " string", " was", " made", " with multiple parameters."; print "<h2>PHP is fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!"; ?>
The following example demonstrates how to use the echo command to output variables and strings:
<?php
$txt1="Learn PHP";
$txt2="example.com";
$cars=array("Volvo","BMW","Toyota");
echo $txt1;
echo "<br>";
echo "Study PHP at $txt2"; //php 双引号内部可包含变量
echo "My car is a {$cars[0]}"; //用大括号 显式的指定这是变量
$txt1="Learn PHP";
$txt2="example.com";
$cars=array("Volvo","BMW","Toyota");
print $txt1;
print "<br>";
print "Study PHP at $txt2";
print "My car is a {$cars[0]}";
?>
PHP5 Data Types
String, Integer, Float, Boolean, Array, Object, NULL (null value).
String
You can place any text in single quotes and double quotes:
<?php $x = "Hello world!"; echo $x; echo "<br>"; $x = 'Hello world!'; //单引号 包括字符串字面量 双引号包含的字符串 可包含变量 echo $x; ?>
Integer
In the following example we will test different numbers. PHPvar_dump()The function returns the data type and value of a variable:
?php $x = 5985; var_dump($x); echo "<br>"; $x = -345; // 负数 var_dump($x); echo "<br>"; $x = 0x8C; // 十六进制数 var_dump($x); echo "<br>"; $x = 047; // 八进制数 var_dump($x); ?>
Float
<?php $x = 10.365; var_dump($x); echo "<br>"; $x = 2.4e3; var_dump($x); echo "<br>"; $x = 8E-5; var_dump($x); ?>
Boolean
Boolean can be TRUE or FALSE.
Array
An array can store multiple values in one variable
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Object
In PHP, objects must be declared.
First, you must declare a class object using the class keyword. A class is a structure that can contain properties and methods.
Then we define data types in the class, and then use the data types in the instantiated class:
<?php
class Car
{
var $color;
function Car($color="green") {
$this->color = $color;
}
function what_color() {
return $this->color;
}
}
function print_vars($obj) {
foreach (get_object_vars($obj) as $prop => $val) {
echo "\t$prop = $val\n";
}
}
// instantiate one object
$herbie = new Car("white");
// show herbie properties
echo "\herbie: Properties\n";
print_vars($herbie);
?>
NULL Value
The NULL value indicates that a variable has no value. NULL is a value with data type NULL.
<?php $x="Hello world!"; $x=null; var_dump($x); ?>
Constants
A constant is an identifier for a simple value. This value cannot be changed during the script. (A constant name does not need the $ modifier.)
Note: Constants can be used throughout the entire script.
To set a constant, use the define() function, whose syntax is as follows:
define(string constant_name, mixed value, case_sensitive = true)
This function has three parameters:
- constant_name: Required parameter, the constant name, i.e., the identifier.
- value: Required parameter, the value of the constant.
- case_sensitive: Optional parameter, specifies whether it is case-sensitive; set to true to indicate case-insensitive.
The following example creates a case-sensitive constant with the value "Welcome to example.com!":
<?php
define("GREETING", "Welcome to example.com!");
echo GREETING;
?>
String functions and string concatenation
<?php
$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2; // 字符串连接运算符 .
echo strlen("Hello world!"); //获取字符串长度
echo strpos("Hello world!","world"); //获取子串位置
//字符串中第一个字符的位置是 0
?>
Operators
<?php
//其他运算符略..
//逻辑运算符 ! && || and or xor
//数组运算符 合并: + 比较:== != === !==
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // $x 和 $y 数组合并
var_dump($z);
var_dump($x == $y);
var_dump($x === $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);
?>
Flow control statements, same as JS
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
else if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
//循环
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
Arrays
<?php
$cars=array("Volvo","BMW","Toyota"); //数组定义 数值数组
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; //访问数组元素
//数组长度count()
$cars=array("Volvo","BMW","Toyota");
echo count($cars); //count() 函数用于返回数组的长度
//遍历数值数组
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");//定义关联数组
echo "Peter is " . $age['Peter'] . " years old.";
//遍历关联数组
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Array Sorting
PHP - Array Sorting Functions
- sort() - sorts an array in ascending order
- rsort() - sorts an array in descending order
- asort() - sorts an associative array in ascending order according to the value
- ksort() - sorts an associative array in ascending order according to the key
- arsort() - sorts an associative array in descending order according to the value
- krsort() - sorts an associative array in descending order according to the key
//sort()
$cars=array("Volvo","BMW","Toyota");
sort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
//rsort()
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
//asort() arsort() 关联数组排序 value
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
arsort($age);
//ksort() krsort() 关联数组排序 key
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
krsort($age);
?>
Superglobal Variables
PHP predefines several superglobal variables, which means they are available in all scopes throughout a script.
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_COOKIE
- $_FILES
- $_ENV
- $_SESSION
$GLOBAL is a global combined array that contains all variables. The variable names are the keys of the array.
<?php
$x = 75;
$y = 25;
function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
$_SERVER is an array containing information such as headers, paths, and script locations. The items in this array are created by the web server. There is no guarantee that every server will provide all items;
<?php echo $_SERVER['PHP_SELF']; // /try/demo_source/demo_global_server.php echo "<br>"; echo $_SERVER['SERVER_NAME']; // example.com echo "<br>"; echo $_SERVER['HTTP_HOST']; // www.example.com echo "<br>"; echo $_SERVER['HTTP_REFERER']; //来由 echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; //浏览器 echo "<br>"; echo $_SERVER['SCRIPT_NAME']; // /try/demo_source/demo_global_server.php //另外$_SERVER对象还包括 SERVER_ADDR, SERVER_PROTOCOL ,REQUEST_METHOD..等属性 ?>
$_REQUEST is used to collect data submitted by HTML forms.
<html> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php $name = $_REQUEST['fname']; echo $name; ?> </body> </html>
$_POST is widely used to collect form data. Specify this attribute in the HTML form tag: "method="post"
<html> <body> <!--页面post给自己--> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php $name = $_POST['fname']; echo $name; ?> </body> </html>
$_GET is also widely used to collect form data. Specify this attribute in the HTML form tag: "method="get".
$_GET can also collect data sent in the URL.
<html> <body> <a href="test_get.php.html">Test $GET</a> </body> </html> //test_get.php <html> <body> <?php echo "Study " . $_GET['subject'] . " at " . $_GET['web']; ?> </body> </html>
PHP Functions
The real power of PHP comes from its functions.
In PHP, more than 1000 built-in functions are provided.
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
//函数传参
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br>";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
//函数返回值
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Magic Variables
There are eight magic constants whose values change depending on their position in the code.
- _LINE__
The current line number in the file. - FILE
The full path and filename of the file. If used inside an included file, the name of the included file is returned. - DIR
The directory of the file. If used inside an included file, the directory of the included file is returned. - FUNCTION
The function name (new in PHP 4.3.0). As of PHP 5 this constant returns the function name as it was defined (case-sensitive). In PHP 4 the value is always lowercase.
<?php
function test() {
echo '函数名为:' . __FUNCTION__ ;
}
test();
?>
- CLASSThe class name (new in PHP 4.3.0). As of PHP 5 this constant returns the class name as it was defined (case-sensitive).
In PHP 4 the value is always lowercase. The class name includes its declared scope (e.g. Foo\Bar). Note that as of PHP 5.4CLASSit also works with traits. When used in a trait method,CLASSit is the name of the class that uses the trait method.
<?php
class test {
function _print() {
echo '类名为:' . __CLASS__ . "<br>";
echo '函数名为:' . __FUNCTION__ ;
}
}
$t = new test();
$t->_print();
?>
- TRAITThe trait name (new in PHP 5.4.0). As of PHP 5.4.0, PHP implements a method of code reuse called traits.
The trait name includes its declared scope (e.g. Foo\Bar).
The inherited member from the base class is overridden by the MyHelloWorld method inserted into the SayWorld trait. Its behavior is the same as the method defined in the MyHelloWorld class. The precedence order is that methods in the current class override trait methods, and trait methods in turn override methods in the base class.
<?php
class Base {
public function sayHello() {
echo 'Hello ';
}
}
trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base {
use SayWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
?>
- METHODThe class method name (new in PHP 5.0.0). Returns the method name as it was defined (case-sensitive).
<?php
function test() {
echo '函数名为:' . __METHOD__ ;
}
test();
?>
- NAMESPACEThe name of the current namespace (case-sensitive). This constant is defined at compile time (new in PHP 5.3.0).
<?php namespace MyProject; echo '命名空间为:"', __NAMESPACE__, '"'; // 输出 "MyProject" ?>
Namespaces
PHP namespaces were added in PHP 5.3. If you have learned C# and Java, namespaces are nothing new. However, they still have considerable significance in PHP.
PHP namespaces can solve the following two types of problems:
- Name collisions between user code and PHP's internal classes/functions/constants.
- Create alias (or shortened) names, improving the readability of source code.
By default, all constants, classes, and function names are placed in the global space, just as they were before PHP supported namespaces.
If a file contains namespaces, the namespace declaration must come before all other code.
< ?php
// 定义代码在 'MyProject' 命名空间中
namespace MyProject;
// ... 代码 ...
//也可以在同一个文件中定义不同的命名空间代码
namespace MyProject1;
// MyProject1 命名空间中的PHP代码
namespace MyProject2;
// MyProject2 命名空间中的PHP代码
// 另一种语法
namespace MyProject3 {
// MyProject3 命名空间中的PHP代码
}
?>
The only legal code before declaring a namespace is a declare statement used to define the encoding of the source file. All non-PHP code, including whitespace, cannot appear before the namespace declaration.
<?php
declare(encoding='UTF-8'); //定义多个命名空间和不包含在命名空间中的代码
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace { // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>
The following code will cause a syntax error:
<html> <?php namespace MyProject; // 命名空间前出现了“<html>” 会致命错误 - 命名空间必须是程序脚本的第一条语句 ?>
Sub-namespaces
<?php
namespace MyProject\Sub\Level; //声明分层次的单个命名空间
//创建了常量 MyProject\Sub\Level\CONNECT_OK,
//类 MyProject\Sub\Level\Connection
//和函数 MyProject\Sub\Level\Connect。
const CONNECT_OK = 1;
class Connection { /* ... */ }
function Connect() { /* ... */ }
?>
Using namespaces
Class names in PHP namespaces can be referenced in three ways:
Unqualified names, or class names without a prefix, e.g. $a=new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespace\foo. If the code that uses foo is global, i.e. code not contained in any namespace, foo will be resolved to foo. Warning: If a function or constant in a namespace is not defined, the unqualified function name or constant name will be resolved to the global function name or constant name.~~Reference without a namespace prefix: by default looks in the current namespace, then in the global namespace.
Qualified names, or names containing a prefix, e.g. $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespace\subnamespace\foo. If the code that uses foo is global, i.e. code not contained in any namespace, foo will be resolved to subnamespace\foo.~~Reference with a relative namespace prefix (similar to a relative path); automatically prepends the namespace of the calling code.
Fully qualified names, or names containing the global prefix operator, e.g. $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. In this case, foo is always resolved to the literal name in the code, currentnamespace\foo.~~Reference with an absolute namespace prefix (similar to an absolute path). The reference path is explicit and no lookup is needed.
file1.php
<?php
namespace Foo\Bar\subnamespace;
const FOO = 1;
function foo() {}
class foo
{
static function staticmethod() {}
}
?>
file2.php
<?php
namespace Foo\Bar;
include 'file1.php';
const FOO = 2;
function foo() {}
class foo
{
static function staticmethod() {}
}
/* 非限定名称 */
foo(); // 解析为函数 Foo\Bar\foo
foo::staticmethod(); // 解析为类 Foo\Bar\foo的静态方法staticmethod。
echo FOO; // resolves to constant Foo\Bar\FOO
/* 限定名称 */
subnamespace\foo(); // 解析为函数 Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // 解析为类 Foo\Bar\subnamespace\foo,
// 以及类的方法 staticmethod
echo subnamespace\FOO; // 解析为常量 Foo\Bar\subnamespace\FOO
/* 完全限定名称 */
\Foo\Bar\foo(); // 解析为函数 Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // 解析为类 Foo\Bar\foo, 以及类的方法 staticmethod
echo \Foo\Bar\FOO; // 解析为常量 Foo\Bar\FOO
?>
Accessing global classes, functions, and constants from within a namespace:
<?php
namespace Foo;
function strlen() {}
const INI_ALL = 3;
class Exception {}
$a = \strlen('hi'); // 调用全局函数strlen
$b = \INI_ALL; // 访问全局常量 INI_ALL
$c = new \Exception('error'); // 实例化全局类 Exception
?>
Namespaces and dynamic language features
PHP's implementation of namespaces is affected by the dynamic features of the language itself. Therefore, if you want to convert the following code to namespaces, access elements dynamically.
//example.php
<?php
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "global";
$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
?>
<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";
include 'example1.php';//全局命名空间和某个命名空间有相同类 函数 和 常量 分别区别访问
$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a = '\namespacename\classname';
$obj = new $a; // prints namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // also prints namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b = '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // prints namespaced
echo constant('namespacename\constname'), "\n"; // also prints namespaced
?>
namespace keyword and __NAMESPACE__ constant
<?php namespace MyProject; echo '"', __NAMESPACE__, '"'; // 输出 "MyProject" ?>
<?php echo '"', __NAMESPACE__, '"'; // 输出 "" ?>
Dynamically creating names with __NAMESPACE__
<?php
namespace MyProject;
function get($classname)
{
$a = __NAMESPACE__ . '\\' . $classname;
return new $a;
}
?>The namespace keyword can be used to explicitly access elements in the current namespace or a sub-namespace. It is equivalent to the self operator in classes.
<?php namespace MyProject; use blah\blah as mine; // see "Using namespaces: importing/aliasing" blah\mine(); // calls function blah\blah\mine() namespace\blah\mine(); // calls function MyProject\blah\mine() namespace\func(); // calls function MyProject\func() namespace\sub\func(); // calls function MyProject\sub\func() namespace\cname::method(); // calls static method "method" of class MyProject\cname $a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname $b = namespace\CONSTANT; // assigns value of constant MyProject\CONSTANT to $b ?>
In PHP, aliases are implemented with the use operator. Below is an example using all three possible ways of importing:
- Importing/using aliases with the use operator
<?php namespace foo; use My\Full\Classname as Another; // 下面的例子与 use My\Full\NSname as NSname 相同 use My\Full\NSname; // 导入一个全局类 use \ArrayObject; $obj = new namespace\Another; // 实例化 foo\Another 对象 $obj = new Another; // 实例化 My\Full\Classname 对象 NSname\subns\func(); // 调用函数 My\Full\NSname\subns\func $a = new ArrayObject(array(1)); // 实例化 ArrayObject 对象 // 如果不使用 "use \ArrayObject" ,则实例化一个 foo\ArrayObject 对象 ?>
- Multiple use statements on one line
<?php use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // 实例化 My\Full\Classname 对象 NSname\subns\func(); // 调用函数 My\Full\NSname\subns\func ?> <p>导入操作是在编译执行的,但动态的类名称、函数名称或常量名称则不是。</p> <ol> <li>导入和动态名称</li> </ol> <pre> <?php use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // 实例化一个 My\Full\Classname 对象 $a = 'Another'; $obj = new $a; // 实际化一个 Another 对象 ?>
- Importing and dynamic names
<?php use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // 实例化一个 My\Full\Classname 对象 $a = 'Another'; $obj = new $a; // 实际化一个 Another 对象 ?>
In addition, the import operation only affects unqualified and qualified names. Since fully qualified names are definite, they are not affected by importing.
- Importing and fully qualified names
<?php use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // instantiates object of class My\Full\Classname $obj = new \Another; // instantiates object of class Another $obj = new Another\thing; // instantiates object of class My\Full\Classname\thing $obj = new \Another\thing; // instantiates object of class Another\thing ?>
Using namespaces: fallback to global functions/constants
In a namespace, when PHP encounters an unqualified class, function, or constant name, it uses different precedence strategies to resolve the name.
- Class names are always resolved to names in the current namespace (an error is raised if not found).Therefore, when accessing internal system classes or class names not contained in a namespace, you must use fully qualified names.
- For functions and constants, if the function or constant does not exist in the current namespace, PHP falls back to using the function or constant in the global space.
<?php
namespace A\B\C;
class Exception extends \Exception {}
$a = new Exception('hi'); // $a 是类 A\B\C\Exception 的一个对象
$b = new \Exception('hi'); // $b 是类 Exception 的一个对象
$c = new ArrayObject; // 致命错误, 找不到 A\B\C\ArrayObject 类
?>
Global space
If no namespace is defined, all class and function definitions are in the global space, just as they were before PHP introduced the concept of namespaces. Prefixing a name with \ indicates that the name is a name in the global space, even when that name is located in another namespace.
<?php
namespace A\B\C;
/* 这个函数是 A\B\C\fopen */
function fopen() {
/* ... */
$f = \fopen(...); // 调用全局的fopen函数
return $f;
}
?>
Order of namespaces (omitted..)
PHP File Handling
Opening files
$file = fopen($fname, mode) // file name, opening mode
- r Read-only. Starts at the beginning of the file.
- r+ Read/Write. Starts at the beginning of the file.
- w Write-only. Opens and clears the file contents; if the file does not exist, creates a new file.
- w+ Read/Write. Opens and clears the file contents; if the file does not exist, creates a new file.
- a Append. Opens and writes to the end of the file; if the file does not exist, creates a new file.
- a+ Read/Append. Opens and writes to the end of the file to preserve the file contents.
- x Write-only. Creates a new file. Returns FALSE and an error if the file already exists.
- x+ Read/Write. Creates a new file. Returns FALSE and an error if the file already exists.
Note: If the fopen() function cannot open the specified file, it returns 0 (false).
<?php
//打开文件
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
//是否到达文件末尾
while(!feof($file))
{
echo fgets($file). "<br>"; //逐行读取文件
//echo fgetc($file); //逐字符读取
}
//关闭文件
fclose($file);
?>
Filesystem functions
- basename() Returns the file name portion of a path.
- chgrp() Changes the file group.
- chmod() Changes the file mode.
- chown() Changes the file owner.
- clearstatcache() Clears the file stat cache.
- copy() Copies a file.
- delete() See unlink() or unset()
- dirname() Returns the directory name portion of a path.
- disk_free_space() Returns the available space in a directory.
- disk_total_space() Returns the total disk capacity of a directory.
- diskfreespace() Alias of disk_free_space().
- fclose() Closes an open file.
- feof() Tests whether the file pointer is at the end of the file.
- fflush() Flushes buffered output to an open file.
- fgetc() Returns a character from an open file.
- fgetcsv() Parses a line from an open file, checking for CSV fields.
- fgets() Returns a line from an open file.
- fgetss() Returns a line from an open file and filters out HTML and PHP tags.
- file() Reads a file into an array.
- file_exists() Checks whether a file or directory exists.
- file_get_contents() Reads a file into a string. ~~Get file contents
- file_put_contents() Writes a string to a file. ~~Write file contents
- fileatime() Returns the last access time of a file.
- filectime() Returns the last modification time of a file.
- filegroup() Returns the group ID of a file.
- fileinode() Returns the inode number of a file.
- filemtime() Returns the last modification time of a file's content.
- fileowner() Returns the user ID (owner) of a file.
- fileperms() Returns the file permissions.
- filesize() Returns the file size.
- filetype() Returns the file type.
- flock() Locks or releases a file.
- fnmatch() Matches a filename or string against a specified pattern.
- fopen() Opens a file or URL.
- fpassthru() Reads data from an open file until the end of the file (EOF) and writes the result to the output buffer.
- fputcsv() Formats a line as CSV and writes it to an open file.
- fputs() Alias of fwrite().
- fread() Reads an open file.
- fscanf() Parses input according to a specified format.
- fseek() Seeks in an open file.
- fstat() Returns information about an open file.
- ftell() Returns the current position in an open file.
- ftruncate() Truncates an open file to a specified length.
- fwrite() Writes to an open file.
- glob() Returns an array containing filenames/directories that match a specified pattern.
- is_dir() Checks whether a file is a directory.
- is_executable() Checks whether a file is executable.
- is_file() Checks whether a file is a regular file.
- is_link() Checks whether a file is a link.
- is_readable() Checks whether a file is readable.
- is_uploaded_file() Checks whether a file was uploaded via HTTP POST.
- is_writable() Checks whether a file is writable.
- is_writeable() Alias of is_writable().
- lchgrp() Changes the group ownership of a symbolic link.
- lchown() Changes the user ownership of a symbolic link.
- link() Creates a hard link.
- linkinfo() Returns information about a hard link.
- lstat() Returns information about a file or symbolic link.
- mkdir() Creates a directory.
- move_uploaded_file() Moves an uploaded file to a new location.
- parse_ini_file() Parses a configuration file.
- parse_ini_string() Parses a configuration string.
- pathinfo() Returns information about a file path.
- pclose() Closes a process opened by popen().
- popen() Opens a process.
- readfile() Reads a file and writes it to the output buffer.
- readlink() Returns the target of a symbolic link.
- realpath() Returns the absolute pathname.
- realpath_cache_get() Returns cache entries.
- realpath_cache_size() Returns the cache size.
- rename() Renames a file or directory.
- rewind() Rewinds the position of a file pointer.
- rmdir() Removes an empty directory.
- set_file_buffer() Sets the buffer size of an open file.
- stat() Returns information about a file.
- symlink() Creates a symbolic link.
- tempnam() Creates a unique temporary file.
- tmpfile() Creates a unique temporary file.
- touch() Sets the access and modification time of a file.
- umask() Changes the file permissions.
- unlink() Deletes a file.
PHP JSON
- json_encode Encodes a variable in JSON format.
- json_decode Decodes a JSON-formatted string and converts it to a PHP variable.
- json_last_error Returns the last error that occurred.
string json_encode ( $value [, $options = 0 ] )
Parameters
value: The value to be encoded. This function only works with UTF-8 encoded data.
options: A bitmask consisting of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
class Emp {
public $name = "";
public $hobbies = "";
public $birthdate = "";
}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";
$e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
$e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters
json_string: The JSON string to be decoded. It must be UTF-8 encoded data.
assoc: When this parameter is TRUE, an array is returned; when FALSE, an object is returned.
depth: An integer parameter that specifies the recursion depth.
options: A bitmask. Currently only JSON_BIGINT_AS_STRING is supported.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
More Tutorials
For more detailed tutorials, see:PHP Tutorial