1. Использование строки
The string can be used as a set of characters, and each character can be accessed independently. Only applicable to single byte characters (letters, numbers, half angle punctuation), not available for Chinese characters (under utf8, 3 bytes in Chinese) $str = "abcd"; echo $str[3]; // d echo $str{0}; // a //Another way You can also use str_split to divide all characters into arrays. $strarr = str_spill ($STR); // also not suitable for Chinese Array ( [0] => a [1] => b [2] => c [3] => d ) function mb_str_split($str){ Return preg_split ('/ (? Bo [1] = > guest )
2. Тип преобразования
Обычно мы знаем, что перед переменными вы можете добавить (int), (строка), (с плавающей точкой) и так далее для выполнения преобразования отображения. Вот преобразование, которое может быть непосредственно преобразовано в null,. (не установлено)//преобразовать в null
$a = 'a'; $a = (unset) $a; // at this time, $a is null //Another way $a = 'a'; unset($a); dd($a); // wrong report PHP Notice: Undefined variable: a in test.php on line 39 Notice: Undefined variable: a in test.php on line 39
3. Обнаружение переменных по isset и пустым, является \
3.1 если isset должен обнаружить, что переменная не существует, он вернет значение false; однако необходимо отметить, является ли сама переменная нулевой, и если да, то она также вернет значение false; в противном случае она вернет значение true. Чтобы облегчить обнаружение существования переменных, вы можете использовать Рекомендуется судить по ключу массива существует
$a = null; $varExists = array_key_exists('a', get_defined_vars()); if($varExists){ Echo 'variable a exists'; }
3.2 пусто, переменная обнаружения не существует, и каждое нулевое значение, значение 0 равно true, в противном случае оно равно false 3.3 is_null, Когда параметр удовлетворяет следующим трем условиям, равно null() вернет значение true, а остальные условия равны 1. Ему присвоено значение null 2. Он еще не назначен 3. Он не определен, что эквивалентно функции unset (). После захода солнца () переменная, она не определена
4. Частичное использование статических
Мы все знаем, что статика может напрямую определять статические переменные и статические методы. Независимо от того, вызываются ли статические переменные и статические методы, их можно вызывать с помощью::, если это класс, их можно вызывать с помощью self, если они находятся во внешнем классе, для вызова используется имя класса, но оно не слишком подробно описано здесь, которые чаще используются. Давайте поговорим о менее часто используемых.
Задержка статической привязки статики в классе;
Delayed static binding is to allow the called class to be referenced in the context of a static inheritance. Delayed binding means that static:: is no longer the class where the current method is defined, but the class where the actual runtime is. (the general meaning is that after the subclass inherits the parent class, a static method or variable is used in the parent class, such as static:: a(), but method a does not exist in the parent class, It exists in the subclass, so it is correct to write like this, and no error will be reported because the static decorated a will be bound to the specific subclass during execution As long as the subclass has this method) Note: it can be used for (but not limited to) static method calls. Self::, representing this class (the class of the current code) Always represents this class, because it has been determined at class compilation time. That is, the subclass calls the parent method, but self does not represent the subclass called. Parent:: represents the parent class Static::, representing this class (the class that calls this method) Class used to reference static calls within the scope of inheritance. At run time, the class represented is determined. Static:: is no longer resolved to the class where the current method is defined, but is calculated at actual run time. In addition to the simple use of static delay binding, there is also a forward call, Forward_static_call_array (), which can only be called in the method, will forward the invocation information (but much more, similar to the eighth point in this section, PHP reflection). The general examples are as follows:
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(); Let's get the answer together:
5. Array_merge и +, объединить массив
5.1 когда слияние массивов объединяет два или более массивов, если имя ключа не числовое, оно будет автоматически объединено вместе, но если есть дубликаты имен ключей, последние перезапишут первые. Если имя ключа является числом, оно автоматически изменит значение индекса на предыдущее приращение в соответствии со значением индекса предыдущего массива, то есть изменит исходное имя ключа.
5.2 + объединить массив: используйте знак + для объединения массива. Если имена ключей совпадают, первые имена ключей будут зарезервированы, и даже если имена ключей являются числами, они не будут переставлены. Эта функция очень полезна для некоторых бизнес-сценариев.
5.3 array_push, просто поместите соответствующее значение в конец массива полностью, исходная структура будет зарезервирована, и все будет взято как новое значение, а имя ключа увеличится с предыдущим. Это отличается от слияния массивов
5.4 массив [объединить], два параметра, первый параметр в качестве ключа нового массива, а второй параметр в качестве значения нового массива. Речь идет не о добавлении новых значений в исходный массив. Таким образом, на самом деле он отличается от вышеперечисленных трех функций. Легко спутать просто по имени.
$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. указатель
Internal pointer to array: Current / POS returns the value of the array unit currently pointed to by the internal pointer, and does not move the pointer. Key returns the key name of the current unit in the array without moving the pointer Next moves the internal pointer in the array one bit forward and returns the value of the current cell after the move. First move, then value. Prev returns the internal pointer of the array to one bit, and returns the value of the current cell to be moved first and then the value. End points the internal pointer of the array to the last cell and returns the value of the last cell Reset points the array's internal pointer to the first cell and returns the value of the first array cell Each returns the current key / value pair in the array and moves the array pointer one step forward. The returned array is a 4-length array composed of key and value. The subscript 0 and key represent key, and the subscript 1 and value represent value After each() is executed, the array pointer stays at the next cell in the array or at the last cell when it hits the end of the array. If you want to traverse the array with each, you must use reset(). 1. The above pointer operation function, except key(), returns false if the pointer moves out of the array. The key () move out returns null. 2. If the pointer is illegal, the next / prev operation cannot be performed, and the reset / end operation can be performed 3. Current / next / prev will also return false if it encounters an empty cell (0 or ""). And each won't! List assigns values in an array to variables. List () is a language structure, not a function. Arrays that can only be used for numeric indexes and assume that numeric indexes start at 0 /*Can be used to exchange values of multiple variables*/ list($a, $b) = array($b, $a); For example: list ($drive, $power) = array ('coffee ',' Brown ',' Cafe '); 1. Copy the array, and its pointer position will also be copied. Special case: if the array pointer is illegal, the copied array pointer will be reset, while the original array pointer will not be changed. [pointer problem] Whoever writes first will open up a new value space. It has nothing to do with who the value of the variable (array variable) is passed to. The array function current() is defined as a write operation, so there is a problem. Foreach traverses the copy of the array, and when it is written, it will open up a new value space. That is, when the foreach loop body writes to the original array, the pointer problem will occur. If the pointer is illegal when a new space is opened, the pointer is initialized. 2. If there is a problem with the pointer position, reset() can be initialized once.
7. Сериализация (сериализация)
#Data transfer is of string type #Serializable except for resource types #When serialization stores data, it stores data itself and data types Functions: 1. When transferring data on the network; 2. To place arrays or objects on the disk Serialization Serialize produces a representation of a storable value string serialize ( mixed $value ) -Returns a string containing a byte stream representing value that can be stored anywhere. -It is good for storing or passing PHP values without losing its type and structure. #Deserialization Unserialize creates PHP values from stored representations mixed unserialize ( string $str [, string $callback ] ) -Operate on a single serialized variable and convert it back to the value of PHP.
8.PHP размышления
Иногда, чтобы создать лучшую структуру кода и повторно использовать код, нам необходимо использовать некоторые языковые функции, которые помогут нам выполнить задачу. Например, для недавно построенного сервиса warehouse Trinity middle нам нужно использовать встроенные функции PHP, такие как вызов массива user func, чтобы просто реализовать распределение. Используйте следующим образом:
class Order{ public function getBasicInfo($orderId, $write = false) { } } $detailServiceInstance = new Order(); $functionName = 'getBasicInfo'; $params [0] = 1000001; // or $params ['orderid '] = 1000001 $params [1] = true; // or $params ['write '] = true call_user_func_array([$detailServiceInstance, $functionName], $params);
Из приведенного выше кода мы видим, что первым параметром call ﹣ user ﹣ func ﹣ array является массив. Значение индекса 0 в массиве является экземпляром класса, а индекс 1-это метод, существующий в экземпляре. Второй параметр-это параметр, требуемый соответствующей функцией, который представлен в виде массива. Вызов ﹣ пользователь ﹣ функция ﹣ массив автоматически изменит порядок параметров, что очень важно. Независимо от того, используется имя числового ключа или имя символьного ключа, конкретные параметры функции должны соответствовать один за другим, чтобы распределение функции могло быть реализовано правильно.
8.1 применение отражения
Используя массив функций пользователя вызова, мы можем просто реализовать распределение, и все параметры понятны. Но если нам нужно использовать эту функцию более гибко, нам нужно ввести механизм отражения PHP, такой как класс ReflectionMethod PHP,
Through this class, we can directly get all kinds of information about specific methods in a class, such as the number of parameters, parameter name, whether there is a default value, etc. The code is as follows:
$object = new Order(); $functionName = 'getBasicInfo'; $reflectionObj = new \ReflectionMethod($object, $functionName); //After passing the above code, you can directly obtain relevant information through $reflectionobj, as follows $reflectionobj - > ispublic(); // you can judge whether the method is public, and isprivate, isprotected, isstatic, etc $reflectionobj - > getparameters(); // you can get all the parameters of the method. It is an array. You can obtain specific parameters for 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()) {// or use isdefaultvalueavailable to check if a default value is available $paramVal = $arg->getDefaultValue(); } $callParams[$arg->name] = $paramVal; } } Specific parameters: https://www.php.net/manual/zh/class.reflectionmethod.php
Кроме того, класс reflectionclass может получать информацию о некоторых классах. Использование аналогично.
8.2 вызов несуществующих методов
__Call & статический вызов (магический метод) Если метод в вызывающем классе не существует или у него нет разрешения на доступ, он автоматически вызовет “метод вызова ()”.. Вызов статического метода, соответствующего вызову, называется статическим. С помощью PHP-отражения код может быть оптимизирован для выполнения некоторых специальных базовых бизнес-функций, например, аналогичные методы используются внутри для рабочих заданий и Тринити.
9. move_uploaded_file
Эта функция является функцией, которая может быть использована после загрузки внешнего файла в фоновом режиме. После загрузки мы будем использовать
move_uploaded_file($tmp_name, $savePath);
Временные файлы, такие как:/TMP/phpwtjzuw, будут удалены, что приведет к проблеме, из-за которой файл не может быть найден, если в следующем коде все еще необходимо использовать переменную $_filesglobal.
10. Опорная передача
При использовании таких функций, как массив? Поп, параметры массива? Pop передаются по ссылке. Иногда параметры записываются непосредственно как возвращаемое значение функции в процессе кодирования. Это запрещено после 5.3, и будут сообщаться о фатальных ошибках (в строгом режиме).
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 From: https://www.php.net/manual/zh/function.array-pop.php The behavior of the function passing parameters by reference changes when it is called by value passing. Previously, the function will accept the parameters passing by value, and now it will throw a fatal error. Previously, any function expecting to pass a reference but passing a constant or literal value when it is called needs to assign the value to a variable before the call. The above comes from: PHP manual appendix porting from PHP 5.2. X to PHP 5.3. X https://www.php.net/manual/zh/migration53.incompatible.php
На самом деле, похоже, что ошибки нет, просто назначьте возвращаемое значение этой функции переменной, а затем передайте переменную в качестве параметра. Например, это часто пишется в коде:
error_reporting(E_STRICT); $testArr = ['a','b','c','c','d']; $popValue = array_pop(array_unique($testArr)); //The above code will report an error and must be used $testArr = ['a','b','c','c','d']; $testArr = array_unique($testArr) $popValue = array_pop($testArr);