Summarize the practical but easy-to-ignore trivia in PHP (recommended)

Source: Internet
Author: User
Tags object serialization sprintf
This article mainly summarizes some in the daily work found, PHP useful but easy to be ignored by people, such as PHP function of the existence of the judgment function, PHP function variable function, and so on, the need to follow the small series of friends to see a detailed introduction it.

This article mainly summarizes some useful small knowledge in PHP, share it for everyone to reference the study, below to see the detailed introduction:

1. Whether the function of PHP function exists

When we create custom functions and understand the use of mutable functions, in order to ensure that the functions called by the program are present, we often use function_exists to determine whether a function exists. The same method_exists can be used to detect whether a class's methods exist.

function func () {}if (function_exists (' func ')) {echo ' exists ';}

class defines whether the class_exists can be used

Class myclass{}//checks for the existence of an if (class_exists (' MyClass ')) {$myclass = new MyClass () before use;}

There are many such checks in PHP, such as whether the file exists file_exists, etc.

$filename = ' Test.txt ', if (!file_exists ($filename)) {echo $filename. ' Not exists. ';}

2. Variable function of PHP function

The so-called mutable function, that is, the function is called by the value of the variable, because the value of the variable is variable, so you can call different functions by changing the value of a variable. Often used in callback functions, function lists, or depending on dynamic parameters to invoke different functions. The variable function is called by the variable name in parentheses.

Function name () {echo ' Jobs ';} $func = ' name '; $func (); Calling a mutable function

Variable functions can also be used on the object's method calls

Class Book {function GetName () {  return ' BookName ';}} $func = ' GetName '; $book = new book (); $book-$func ();

Static methods can also be dynamically called through variables

$func = ' getspeed '; $className = ' Car '; Echo $className:: $func (); Dynamic invocation of static methods

In a static method, $this pseudo-variable is not allowed. You can use Self,parent,static to invoke static methods and properties internally.

Class Car {private static $speed = ten;  public static function GetSpeed () {  return self:: $speed;}  public static function SpeedUp () {  return self:: $speed +=10;}} Class Bigcar extends Car {public static function start () {  parent::speedup ();}} Bigcar::start (); Echo Bigcar::getspeed ();

3. Advanced features of PHP classes and objects

Object comparison, when all the properties of two instances of the same class are equal, you can use the comparison operator = = To determine whether a two variable is a reference to the same object, you can use the congruent operator = = =.

Class Car {} $a = new car (), $b = new Car (), if ($a = = $b) echo ' = = '; Trueif ($a = = = $b) echo ' = = = '; False

Object replication, in some special cases, you can copy an object by using the keyword clone, at which point the __clone method is called, and the value of the property is set by this magic method.

Class Car {public $name = ' car ';  Public Function __clone () {  $obj = new Car ();  $obj->name = $this->name; }} $a = new car (); $a->name = ' new car '; $b = clone $a; var_dump ($b);

Object serialization, which can be serialized as a string by the Serialize method, used to store or pass data, and then deserialize the string into an object when needed by Unserialize.

Class Car {public $name = ' car ';} $a = new Car (); $str = serialize ($a); The object is serialized into a string echo $str. ' <br> '; $b = Unserialize ($STR); Deserializes to Object Var_dump ($b);

4, PHP string to get the length of the string

PHP has a magical function that can get the length of a string directly, and this function is strlen ().

$str = ' Hello '; $len = strlen ($STR); echo $len;//Output is 5

The strlen function is very good at calculating English characters, but if you have Chinese characters, what should I do to calculate the length?

You can use the Mb_strlen () function to get the Chinese length in a string.

$str = "I love You"; Echo Mb_strlen ($str, "UTF8");//Results: 3, the UTF8 here means that the Chinese encoding is UTF8 format, Chinese generally use UTF8 encoding

5. Formatted string of PHP string

If there is a string $str = ' 99.9 '; how do you make this string 99.90?

We need to use PHP's formatted string function sprintf ()

Function Description: sprintf (format, string to convert)

Return: Well-formed string

$STR = ' 99.9 '; $result = sprintf ('%01.2f ', $str); echo $result;//Results show 99.90

Explain the format in the example above

What does this%01.2f mean?

1, this% symbol is the beginning of the meaning, written at the top indicates that the specified format began. That is, the "starting character" until the "convert character" appears, even if the format is terminated.

2, followed by the% symbol is 0, is the "fill in the blanks", that is, if the location is empty, fill with the total.

3, after 0 is 1, this 1 is to stipulate that the entire string occupies more than 1 digits (decimal point is also counted as a placeholder).

If you change 1 to 6, the value of the $result will be 099.90.

Because, after the decimal point must be two bits, 99.90 altogether 5 occupies, now needs 6 occupies, therefore fills with the zero.

4, after the%01 of the. 2 (point 2) is very well understood, it means that the number after the decimal point must occupy 2 bits. If this is the $STR value is 9.234, the $result value will be 9.23.

Why is the 4 gone? Because after the decimal point, according to the above rules, must and only can occupy 2 bits. However $str value, 3 digits after the decimal point, so the mantissa 4 is removed, leaving only 23.

5. Finally, end with F "convert character".

6, the string of the PHP string escape

PHP string Escape functionaddslashes()

Function Description: Used to add an escape character to a special character, returns a string

Return value: An escaped string

$str = "What ' s your name?"; echo addslashes ($STR);//output: what\ ' s your name?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.