导图社区 PHP基础入门
学习路径:讯飞AI大学《PHP编程入门》 转载请注明出处 MindMaster @Tracy
编辑于2020-07-07 09:30:00PHP
Syntax
document type
<?php ... ?>
remove ?> if file ends with PHP code
<?= "hello\n"; ?>
<? echo "hello\n"; ?>
comment
#comment
//comment
/* comment */
output
echo function()."\n";
echo "string here: $num"."\n";
//string here: 123
same as echo, but returns 1 or 0 as well
var_dump
dumps variable info
print_r
prints variable info in a more human-readable way
Scalar types
boolean
true、false、TRUE、FALSE
integer
567
//decimal
0123
//octadecimal
0x1A
//hexadecimal
0b1101
//binary
float
1.234
1.2e3
//1200
7E-10
//7.0E-10
float precision error:
$epsilon = 0.00001; if (abs($a-$b) < $epsilon) { echo "true"; } else { echo "false"; }
string
escape
"\n" OR PHP_EOL
"some string $str"
//some string Greet in Hong Kong
"bunchofstring{$str}"
//bunchofstringGreet in Hong Kong
NO escape
'\n'
'some string $str'
//some string $str
"bunchofstring$str"
//bunchofstring$str
'string of multiple lines'
OR "
array index:
$str[0]
//G
$str[3] = 'a';
//Great in Hong Kong
Replaces with the first character only if ' ' contains multiple
functions:
strlen($str)
substr($str, 2, 4)
//eet
returns $str[2] to $str[4]
substr_replace($str, "Beijing from", 6, 7)
//Greet Beijing from Kong
replace starting from $str[6] for 7 characters
declaration:
$var_name = 123456;
get variable type:
gettype($var_name)
Varaible info:
var_dump($var_name);
//int(123456)
//bool(true)
var_dump(expression: 25/7);
//float(3.5714285714286)
var_dump((int)(25/7));
//int(3)
var_dump(round(val: 25/7));
//float(4)
var_dump($str)
//string(5) "hello"
Compound types
array
$name = array( "Amy"=>3, "17", "David", "58"=>"Cathy", 58.6=>"Carmen", "Elmo", - 888=>"last" );
OR $name = ["Amy"...]; for PHP5.4+
keys are:
["Amy"], [0], [1], [58], [59], [-888]
keys:
string
float in string form REMAINS string
int
float TO int (round down)
int in string form TO int
only keep the last element for duplicated keys
add elements:
$name[] = "new name";
key indexing is minimum
$name["girl"] = "new girl";
functions:
count($name)
$name = array_values($name);
re-indexing
unset($name[0]);
delete name[0]
can put array in an array
object
class foo { function do() { ...; } }
$obj = new foo; $obj->do();
OR foo::do();
OR call_user_func(array('foo', 'do');
callable
function myfunc($arg) { ...; }
myfunc($param);
OR call_user_func('myfunc', $param);
resource
$f = fopen($filename, "w");
get_resource_type($f)
NULL
undefined variables
$var = null;
unset($var);
Type-casting
AUTO string TO int/float
$foo = "1";
string //ASCII49
$foo *= 2;
int //2
$foo *= 1.3;
float //1.3
$foo = 5 * "12.0th day of Christmas";
float //60
with warning
$foo = 5 + "letters before 12";
int //5
with warning
settype()
settype($foo, "float");
settype($foo, "integer");
TO boolean
true
(bool) "false"
(bool) -2.3
(bool) array(5)
false
(bool) ""
(bool) 0
(bool) array()
intval()
$to_int = intval(true)
//1
$to_int = intval(12.7)
//12
object TO array
class A { private $a; } $arr = (array) new A();
//array(1) { [" A a"]=>NULL }
array TO object
$obj = (object) array('1'=>'foo');
isset($obj->{'1'})
//true
key($obj)
//1
Defining variables
$var_name = /*value*/ ;
cap-sensitive
global scope:
declare global variables in local function
$var = "global" ;
function localfunc() { $var = "local"; } localfunc(); echo $var;
//global
global $var unchanged
function localfunc() { global $var; $var = "local"; } localfunc(); echo $var;
//local
assigns global $var to "local" directly
static
static $a = 0;
variable
$a = "b"; $$a = "hello";
in $a, //"b" in $b, //"hello"
$list = arr; $$list = ['one', 'two', 'three']; ${$arr[1]} = "hi"; $arr[1] = "bye";
in $two, //"hi"
//array(3) { [0]=>"one", [1]=>"bye", [2]=>"three" }
predefined
$GLOBALS
array of all global variables (inc. system environment variables)
function fun() { $GLOBALS['var'] = "new value"; echo $GLOBALS['var']; } fun(); echo $var;
//new value //new value
$_SERVER、$_GET、$_POST、$_FILES、$_REQUEST、$_SESSION
$_ENV、$COOKIE
$php_errormsg
$http_response_header
$argc、$argv
Defining constants
user defined
define("CONST_NAME", "const_value");
OR const CONST_NAME = "const_value";
scalar types only
don't begin const name with __
no scope constraint
magic
__FILE__
full path and filename of file
__DIR__
directory of file
OR dirname(__FILE__)
__LINE__
current line number of file
__FUNCTION__
name of function
{closure} if anonymous
__METHOD__
name of class method aka. name of class and function
__CLASS__
namespace\name of class
__TRAIT__
namespace\name of trait
__NAMESPACE__
name of namespace
ClassName::class
name of fully qualified class
Operators
priority
clone new [] ** ++ -- ~ (int) (float) (string) (array) (object) (bool) instanceof ...(same as C++)
special arithmetic
**
exponential
===
same value AND same type
<>
same as != (after type-casting)
!==
different value OR different type
<=>
returns an integer <. =, >0 respectively
PHP7+
?? ... ?? ...
returns first defined operand not NULL
if all undefined and not NULL, return NULL
and or
execution
`ls -lh`
executes as shell command
type
$obj instanceof $myclass
check if $obj is an instance of the class $myclass
string
.
join strings
.=
join to current string
array
+
join arrays
can use special arithmetic operators
Control structures
if() else{}
switch() {case: }
for(;;){}
foreach($arr as &$val) {}
$arr must be of type array or object
operating on $val will change respective $arr[i]
while{}, do{} while()
break, return, continue, goto
Functions
function func_name($arg1, $arg2 = 0) {}
can be called anywhere unless defined in condition
if ($sth) { function conditional_func() {} }
NO overload/override/redefine
referencing &
function func(&$arg) {}
change the content of the original variable directly
NO pointer / address usage
internal
phpinfo()
is_bool()
var_dump()
anonymous (closures)
call_user_func(function($arg){}, "some arguments");
OOP
class Base { }
private / protected / public
variable or function
construct
/*type*/ function __construct($v) {...}
//prioritized method
/*type*/ function Base() {}
destruct
/*type*/ function __destruct() {}
copy
/*type*/ function __clone() {}
keywords
$this->
points to the current instance
e.g. definition
$this->var = $v;
self::
points to static members in class
e.g. singleton pattern
private static $instance = null;
//in construction self::$instance = new self();
parent::
points to base class
e.g. in derived
class Derive extends Base { }
can extend only 1 base
//in construction parent::__construct($v); $this->w = $w;
static
static variable
//in member func return self::$var;
//in derive member func return parent::$var;
echo Base::$var;
static function
Base::statFunc();
const
const data
//in member func echo self::constant;
echo Base::constant;
abstract
abstract class A { //declare abstract functions }
class B extends A { //define all abstract functions in A }
interface
interface iTemp { //declare functions }
class Temp implements iTemp { //define functions in iTemp }
can implement >1 interface
trait
trait Tr { }
class Derive extends Base { use Tr; }
function calling priority:
1. Derive
2. Tr
3. Base
iteration
iterates all member variables visible in the calling scope
foreach ($this as $key=>$value) { //echo "$key => $value"; }
magic
__construct
__destruct
__toString
public function __toString() { return $this->$str; }
echo $instance;
namespace
CAN't have any content before <?php if namespace is defined
define
namespace nspc;
call under nspc:
\nspc\func();
OR func();
$a = new \nspc\ClsName();
OR $a = new ClsName();
\nspc\StaticCls::method();
OR StaticCls::method();
require_once(example.php)
//in example.php namespace nspc\sub;
call under nspc:
\nspc\sub\func();
OR sub\func();
echo \nspc\sub\CONSTANT;
OR echo sub\CONSTANT;
\nspc\sub\StaticCls::method();
OR sub\StaticCls::method();
dynamic under nspc:
$x = 'nspc\ClsName'; $obj = new $a;
OR $x = '\nspc\ClsName'; $obj = new $a;
$b = 'dynam\funcname; $b();
OR $b = '\dynam\funcname; $b();
echo constant('nspc\CONSTANT');
OR echo constant('\nspc\CONSTANT');
error
error_reporting(/*level*/);
any binary number or constant
1 E_ERROR
fatal error
2 E_WARNING
runtime warning
will not stop running
4 E_PARSE
syntax parsing warning during compilation
8 E_NOTICE
runtime notice
displays all possible errors
16/32 E_CORE_ERROR/WARNING
E_ERROR/WARNING for initialization of PHP engine core
64/128 E_COMPILE_ERROR/WARNING
E_ERROR/WARNING FOR Zend script engine
256/512/1024 E_USER_ERROR/WARNING/NOTICE
E_ERROR/WARNING/NOTICE by users
trigger_error()
2048 E_STRICT
give code suggestions
4096 E_RECOVERABLE_ERROR
fatal errors that can be caught by users (else, E_ERROR)
set_error_handler()
8192 E_DEPRECATED
runtime notice for unsupported codes in future versions
16384 E_USER_DEPRECATED
E_DEPRECATED by users
trigger_error()
30719 E_ALL
all error levels except E_STRICT
error_log(/*msg*/, /*msg type (int)*/, /*dst (e.g. error.log)*/);
ini_set(/*var name*/, /*value (int)*/);
function MyErrorHandler($errno, $errstr, $errfile, $errline) { if (!(error_reporting()) & $errno) return false; switch ($errno) { case E_USER_ERROR: echo ... exit(1); break; case ... default: echo "Unknown ..."; break; } }
set_error_handler("myErrorHandler");
exceptions
function func($var) { if (/*invalid $var*/) throw new Exception(/*msg*/, /*code (int)*/); else return /*func result*/; }
try { $result = func("input"); } catch (Exception $exception) { var_dump($exception->getMessage()); exit; }
echo $result; exit;
user-defined exception
class MyException extends Exception { public function __construct($message = "", $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); } public function __toString() { return __CLASS__.": displays exception code and message"; } public function customFunc() {...} }
extends system class Exception
//in class Exception implements Throwable protected $message, $code, $file, $line final private function __clone(){}