PHP knowledge point -1

1. Use of a string

可将字符串当作一个字符的集合来使用,可独立访问每个字符。仅适用于单字节字符(字母、数字、半角标点符号),像中文等不可用(utf8下,中文3字节表示)
$str = "abcd";
echo $str[3];   // d
echo $str{0};   // a
//另一种方式
也可以使用str_split把所有字符分割成数组。
$strArr = str_spilt($str);   //同样不适合中文
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
function mb_str_split($str){
    return preg_split('/(?<!^)(?!$)/u', $str );   //反向预搜索
}
$str='博客';
mb_str_split($str);
打印结果如下:
Array
(
    [0] => 博
    [1] => 客
)

2. Conversion Type

Usually we know that before the variable plus (int), (string), (float) display or the like to convert, the following describes a can be converted directly to null conversion.
(unset) // converted to NULL

$a = 'a';
$a = (unset)$a;  //此时$a 为 NULL
//换种方式
$a = 'a';
unset($a);
dd($a);
//报错
PHP Notice:  Undefined variable: a in test.php on line 39

Notice: Undefined variable: a in test.php on line 39

3.isset and empty, is_null detection of variables

3.1 isset to detect variable does not exist, return false; Note, however, whether the variable itself is Null value, and if so, also return false; return true not meet up.
In order to facilitate detection variable exists, using
recommended array_key_exists Analyzing

$a = null;
$varExists = array_key_exists('a', get_defined_vars());
if($varExists){
        echo '变量a是存在的';
}


3.2 empty, detection variable is not present, the respective null, 0 values are true, otherwise to false
3.3 is_null to
the time when the parameters satisfy the following three cases, is_null to () will returns TRUE, the other situation is FALSE
. 1, which is assigned is NULL
2, it has no value
after 3, it is not defined, the equivalent of unset (), a variable unset (), not that it is not defined

4.static part usage

We all know that static can directly define static variables and static methods, either call the static variables and static methods can be called using ::, if this is a class, use the self to call, if it is in the class
outside, use the class name call, but here its not too much to say, these are more commonly used. Not commonly used under the following talk.

static delay class static binding;

延迟静态绑定是指允许在一个静态继承的上下文中引用被调用类。
延迟绑定的意思为:static::不再为定义当前方法所在的类,而是实际运行时所在的类。
(总的意思就是子类继承了父类后,父类中使用了一个静态方法或变量,如static::A(), 但方法A不存在于父类中,
存在于子类中,这样写是正确的,不会因为方法不存在而报错,因为static 修饰的A 会在执行过程中,绑定到具体的子类
上,只要保证子类有此方法即可)
注:它可以用于(但不限于)静态方法的调用。
self::,代表本类(当前代码所在类)
    永远代表本类,因为在类编译时已经被确定。
    即,子类调用父类方法,self却不代表调用的子类。
parent:: 代表父类
static::,代表本类(调用该方法的类)
    用于在继承范围内引用静态调用的类。
    运行时,才确定代表的类。
    static::不再被解析为定义当前方法所在的类,而是在实际运行时计算的。
除了简单的static延迟绑定的用法,还有一种转发调用,
forward_static_call_array()(该函数只能在方法中调用)将转发调用信息(不过多赘述,类似于本节的第8点,PHP反射),
概括实例如下:
class A {
    public static function fooStatic() {
        static::who();
    }
    public static function who() {
        echo __CLASS__."aaa\n";
    }
}
class B extends A {
    public static function testStatic() {
        A::fooStatic();
        B::fooStatic();
        C::fooStatic();
        parent::fooStatic();
        self::fooStatic();
    }
    public static function who() {
        echo __CLASS__."bbb\n";
    }
}
class C extends B {
    public static function who() {
        echo __CLASS__."ccc\n";
    }
}
C::testStatic();
大家一起来得到答案:

5. array_merge and + merge array

5.1 array_merge merge two or more arrays of time, if a non-numeric keys are automatically merged together, but if the duplicate key name, the latter overwrite the previous. If the key figures named, it will be based on the index value before an array automatically changes back to the previous index value is incremented, that will change the original key name.

5.2 + merge array, use the + merge array, the case of the same key name, key name appears first will be retained, even if the key name and a number, it will not be rearranged, the characteristics of the part of the business scene will be very it works.

5.3 array_push, just completely into the corresponding value end of the array, the original structure is retained, as a whole new value, key name followed by an increasing before. This distinction array_merge

5.4 array_combine, two parameters, the first parameter, as the key of the new array, the second parameter values ​​of the new array. Not add new value to the existing array. In fact, he was so different from the three above action. Light Judging from the name confusion.

$a = ['a', 'b', 'c'];
$b = ['5' => 'test'];
$c = [1, 2, 3];

$arrayMerge   = array_merge($a, $b);
$arrayPlus    = $a + $b;
$arrayCombine = array_combine($a, $c);
array_push($a, $b);
// $arrayMerge
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => test
)
// $arrayPlus
Array
(
    [0] => a
    [1] => b
    [2] => c
    [5] => test
)
// $arrayCombine
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
// array_push
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => Array
        (
            [5] => test
        )

)

6. Pointer

数组的内部指针:
current/pos 返回当前被内部指针指向的数组单元的值,并不移动指针。
key         返回数组中当前单元的键名,并不移动指针
next        将数组中的内部指针向前移动一位,并返回移动后当前单元的值。先移动,再取值。
prev        将数组的内部指针倒回一位,并返回移动后当前单元的值先移动,再取值。
end         将数组的内部指针指向最后一个单元,并返回最后一个单元的值
reset       将数组的内部指针指向第一个单元,并返回第一个数组单元的值
each        返回数组中当前的键/值对并将数组指针向前移动一步。
            返回的是一个由键和值组成的长度为4的数组,下标0和key表示键,下标1和value表示值
在执行each()之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()。
1. 以上指针操作函数,除了key(),若指针移出数组,则返回false。而key()移出则返回null。
2. 若指针非法,不能进行next/prev操作,能进行reset/end操作
3. current/next/prev     若遇到包含空单元(0或"")也会返回false。而each不会!

list    把数组中的值赋给一些变量。list()是语言结构,不是函数。
仅能用于数字索引的数组并假定数字索引从0开始
/* 可用于交换多个变量的值 */ 
list($a, $b) = array($b, $a);
例:list($drink, , $power) = array('coffee', 'brown', 'caffeine');
1. 复制数组,其指针位置也会被复制。
    特例:如果数组指针非法,则拷贝的数组指针会重置,而原数组的指针不变。
    【指针问题】
        谁第一个进行写操作,就会开辟一个新的值空间。与变量(数组变量)值传递给谁无关。
        数组函数current()被定义为写操作,故会出现问题。
        foreach遍历的是数组的拷贝,当被写时,才会开辟一个新的值空间。
            即,foreach循环体对原数组进行写操作时,才会出现指针问题。
            如果开辟新空间时指针非法,则会初始化指针。
2. 如果指针位置出现问题,则reset()初始化一下就可解决。

7. serialization (serialization)

# 数据传输均是字符串类型
# 除了资源类型,均可序列化
# 序列化在存放数据时,会存放数据本身,也会存放数据类型
作用:1.在网络传输数据时;2.为了将数组或对象放在磁盘时
# 序列化
serialize        产生一个可存储的值的表示
string serialize ( mixed $value )
- 返回字符串,此字符串包含了表示value的字节流,可以存储于任何地方。
- 有利于存储或传递 PHP 的值,同时不丢失其类型和结构。
# 反序列化
unserialize        从已存储的表示中创建PHP的值
mixed unserialize ( string $str [, string $callback ] )
- 对单一的已序列化的变量进行操作,将其转换回PHP的值。

8.PHP reflection

Sometimes we order we can build better code structure, and can reuse code, you need to use some features of the language to help us complete the task, such as our new warehouse this trinity_middle_service, we need to use PHP native functions, as call_user_func_array, it can be simple to achieve distribution. Used as follows:

class Order{
    public function getBasicInfo($orderId, $write = false)
    {
    }
}
$detailServiceInstance = new Order();
$functionName = 'getBasicInfo';
$params[0] = 1000001;    //或 $params['orderId'] = 1000001
$params[1] = true;       //或 $params['write'] = true
call_user_func_array([$detailServiceInstance, $functionName], $params);

As can be seen from the above code, the first parameter is call_user_func_array array that is a subject of the example class 0, is the subject of the method of this Example 1 present; i.e., the second parameter corresponding to a desired function parameters the argument is an array form, call_user_func_array automatically in sequence corresponding to each parameter, so here, the order of the parameters is important, whether it is the use of numeric keys or character keys, function must correspond specific parameters, so as to correct implementation of the distribution function.

8.1 Application of reflection

Use call_user_func_array, we can simply achieve distribution, and various parameters, but also very clear. But if you need a more flexible use of this function, we also need to introduce reflection of PHP, such as PHP comes ReflectionMethod class,
all kinds of information we can use this class to get directly to a specific class of methods, such as parameters The number, parameter name, if there is a default value, and so on. code show as below:

$object = new Order();
$functionName = 'getBasicInfo';
$reflectionObj = new \ReflectionMethod($object, $functionName);
//通过以上的代码后,就可以直接通过$reflectionObj获取相关信息了,如下
$reflectionObj->isPublic();   //可判断该方法是否为公有方法, 还有isPrivate, isProtected, isStatic等等
$reflectionObj->getParameters();   //可获取该方法所有参数,是个数组,可 foreach获取具体的参数
foreach($reflectionObj->getParameters() as $arg) {
    if(array_key_exists($arg->name, $params)) {
        $callParams[$arg->name] = $params[$arg->name];
    } else {
        $paramVal = null;
        if ($arg->isOptional()) {  // 或使用isDefaultValueAvailable, 检测是否有可用的默认值
            $paramVal = $arg->getDefaultValue();
        }
        $callParams[$arg->name] = $paramVal;
    }
}
具体参数: https://www.php.net/manual/zh/class.reflectionmethod.php

There ReflectionClass can get some information like usage are similar.

8.2 Method call does not exist

__call & __callStatic (magic method)
when calling a class does not exist or is no way of access, it will automatically call __call () method. __Call and the corresponding static method call is __callStatic, with PHP reflection, the code optimized on the basis of special service features to do,
such as work orders, we are used inside the trinity like.

9. move_uploaded_file

This function is a function of the front file upload files to the background might be used, after uploading, we will pass $ _FILES [ 'file'] [ 'tmp_name'] (after the file upload address), use

move_uploaded_file($tmp_name, $savePath);

It will temporarily saved to the database such as: / tmp / phpwTJzUw file to move away, cause if the code behind have to use $ _FILES global variable when the problem can not find the file will appear.

10. The transmission reference

When using array_pop other functions, parameters are passed by reference array_pop, sometimes in the encoding process parameters will be written directly to the return value of the function, so in the future 5.3 is not allowed, it will report a fatal error (in strict mode).

You will see:
PHP Strict Standards:  Only variables should be passed by reference in - on line 3

Strict Standards: Only variables should be passed by reference in - on line 3
d
以上来自于: https://www.php.net/manual/zh/function.array-pop.php

按引用传递参数的函数在被按值传递调用时行为发生改变. 此前函数将接受按值传递的参数, 现在将抛出致命错误. 之前任何期待传递引用但是在调用时传递了常量或者字面值 的函数, 需要在调用前改为将该值赋给一个变量。
以上来自于:PHP手册附录从PHP 5.2.x 移植到 PHP 5.3.x 部分
https://www.php.net/manual/zh/migration53.incompatible.php

And actually looks nothing wrong, just need to assign the function returns a value to a variable, then the variable as a parameter passed on it.
For example, in the code often wrote:

`` `
The error_reporting (E_STRICT);
$ testArr = [ 'A', 'B', 'C', 'C', 'D'];
$ = popValue array_pop (array_unique (testArr $));
the above code // error, you must use
$ testArr = [ 'A', 'B', 'C', 'C', 'D'];
$ testArr = array_unique (testArr $)
$ popValue array_pop = ($ testArr);

Guess you like

Origin www.cnblogs.com/hzqyihui/p/11653666.html
Recommended