[Interview those things one] PHP basics

/**
 * Question 6: How to realize the method of intercepting Chinese strings without garbled characters (mb_* series of functions), first: you need to open the extension=php_mbstring.dll extension, the result: "you"
 */  
  
echo mb_substr("你好",0,1,"gb2312")."<br/>";
/**
 * Question 7: Write code to display client and server IP in PHP
 */  
  
echo $_SERVER['REMOTE_ADDR'];//Client IP  
echo $_SERVER['SERVER_ADDR'];//Server IP  
echo $_SERVER['PHP_SELF'];//Result: "/index.php" The name of the current script (excluding the path and query string)  
echo $_SERVER["HTTP_REFERER"];//Link to the source url of the current page  
echo gethostbyname("www.v1pin.com");//Get the IP address of the specified domain name  
echo getenv("REMOTE_ADDR");//Get the client IP address  
echo getenv("SERVER_ADDR");//Get the server IP address
/**
 * Question 8: IFNULL control flow function in mysql; IFNULL()
 * IFNULL():
 * (1) It has two parameters, and the first parameter is judged.
 * (2) If the first parameter is not NULL, the function will return the first parameter to the caller; if it is NULL, it will return the second parameter;
 * E.g:
 *      SELECT IFNULL(1,2), IFNULL(NULL,10), IFNULL(4*NULL,'false');//结果:"1 10  false"
 */
/**
 * Question 9: Briefly describe the difference between include and require?
 * Same point:
 * (1) Both include and require can include another file into the current file
 * Similarities and differences:
 * (1) When using include, the system will report a warning-level error when the included file does not exist, but it does not affect the subsequent execution of the program.
 * (2) When using require, when the included file does not exist, the system will first report a warning-level error, and then report a fatal error, which will terminate the subsequent execution of the program.
 * (3) require will only interpret the included files once, and will not interpret the second time, so the efficiency is relatively high; while include will repeatedly interpret the included files
 * (4) The loading timing is different: require loads the include file before running, include loads the include file at runtime
/**
 * Question 10: How to get a specified character in a string?
 */  
  
 $str="abcdefg";  
 echo $str{2}."<br/>";  
/**
 * Question 13: Difference between addslashes() and htmlspecialchars()
 *
 * the difference:
 
 * (1) The addslashes() function mainly adds a backslash before the specified predefined characters. These predefined characters mainly include:
 *
 * apostrophe(')
 * Double quotes(")
 * backslash (\)
 *      NULL
 *
 The main function of the * addslashes() function is to ensure that these predefined characters can be correctly stored in the library, that's all
 *
 *
 * (2) The htmlspecialchars() function converts some predefined characters into HTML entities. These predefined characters mainly include:
 *
 *       
 * & (an ampersand) becomes &
 * " (double quotes) becomes "
 * ' (single quote) becomes '
 * < (less than) becomes <
 * > (greater than) becomes >
 *
 * echo htmlspecialchars($str, ENT_COMPAT); //default, only encode double quotes
 * echo htmlspecialchars($str, ENT_QUOTES); //encode double and single quotes
 * echo htmlspecialchars($str, ENT_NOQUOTES);//Do not encode any quotes
 *
 */  
//Question 17: How to use the array_multisort() function to sort multidimensional arrays?  
//Simulate the records queried from the database (hint: two-dimensional array)  
$arr[] = array("age"=>20,"name"=>"小强");  
$arr[] = array("age"=>21,"name"=>"李伟");  
$arr[] = array("age"=>20,"name"=>"小亮");  
$arr[] = array("age"=>22,"name"=>"黎明");  
   
foreach ($arr as $key=>$value){  
    $age[$key] = $value['age']; //sort field "age"  
    $name[$key] = $value['name'];//sort field "name"  
}  
  
/**
 * 1. Sort the $arr array
 * First sort by age in descending order, if the age is the same, then sort by name, similar to order by in sql
 * 2. Notes:
 * (1) $age and $name are equivalent to the "age" and "name" column fields of the data table, similar to "order by age desc, name asc"  
 * (2) Sort order flag:
 * SORT_ASC - sort in ascending order
 * SORT_DESC - sort in descending order
 * (3) Sort type flag:
 * SORT_REGULAR - compare items in the usual way
 * SORT_NUMERIC - compare items by numerical value
 * SORT_STRING - compare items as strings
 * (4) The default values ​​of sort flags are: SORT_ASC and SORT_REGULAR
 * (5) The sorting flag specified after each one-dimensional array is only valid for this one-dimensional array, and a one-dimensional array cannot specify two similar sorting flags
 * (6) This function will change the number index, other indexes will not change
 *
 */  
array_multisort($age,SORT_NUMERIC,SORT_DESC,$name,SORT_STRING,SORT_ASC,$arr);  
echo "<pre>";print_r($arr);exit;  
/**
 * result: equivalent to "select * from user order by age desc,name asc";
 * Array(
 *   [0] => Array
 *       (
 *           [age] => 22
 * [name] => dawn
 *       )
 *   [1] => Array
 *       (
 *           [age] => 21
 * [name] => Li Wei
 *       )
 *   [2] => Array
 *       (
 *           [age] => 20
 * [name] => Xiao Liang
 *       )
 *   [3] => Array
 *       (
 *           [age] => 20
 * [name] => Xiaoqiang
 *       )
 * )
 */
/**
 * Question 27: Swap keys and values ​​in an array
 */  
$a=array(  
    0=>"Dog",  
    1=>"Cat",  
    2=>"Horse"  
);  
echo "<pre>";  
print_r(array_flip($a));  
  
/**
 * The result processed by the array_flip() array function:
 * Array(
 *   [Dog] => 0
 *   [Cat] => 1
 *   [Horse] => 2
 *  )
 */
/**
 * Question 39: Turning on the safe_mode option in the php.ini file will affect the application of which functions? Name at least four
 *
 * Answer: It mainly affects file operation functions, program execution functions, etc.
 * Such as: pathinfo(), basename(), fopen(), exec(), etc.
 */  
/**
* Question 41: How to control the size of the uploaded file through the form?
*
* (1) Answer: In the form, the size of the uploaded file is controlled by the hidden field MAX_FILE_SIZE, which must be placed before the file field to work.
*
* (2) Analysis: Control uploading files on the client side, the enctype and method attributes in the applied form, and the hidden field MAX_FILE_SIZE
* enctype="multipart/form-data" //Specify the form encoding data method
* method="post" //Specify the transmission method of data
* <input type="hidden" name="MAX_FILE_SIZE" value="10000" /> //Control the size of the uploaded file (in bytes) through the hidden field, the value cannot exceed the upload_max_filesize option setting in the php.ini configuration file the value of
*/
/**
 * Question 43: How to convert 1234567890 to 1,234,567,890 in the form of comma separated every three digits?
 */  
echo number_format("1234567890")."<br/>"; //result: 1,234,567,890 default comma as separator        
echo number_format("1234567890",2)."<br/>"; //Result: 1,234,567,890.00 Parameter 2 - specify the number of decimal places  
echo number_format("1234567890",2,",",".")."<br/>"; //Result: 1.234.567.890,00 Parameter 2 - Specify the number of decimal places Parameter 3 - Specify the character to replace the decimal point symbol String parameter 4 - Specifies the string to use as the thousands separator  
/**
 * Question 45: What is the difference between stripos(), strpos(), strripos(), strrpos() string functions?
 *
 * (1) stripos(): Returns the position of the first occurrence of a string in another string (case insensitive)
 * (2)strpos() : Returns the position of the first occurrence of a string in another string (case-sensitive)
 * (3) strripos(): Find the last occurrence of a string in another string (case-insensitive)
 * (4) strrpos(): Find the last occurrence of a string in another string (case sensitive)
/**
 * Question 48: How to use php environment variables to get the content of a web page address?
 * 如:"http://www.baidu.com/index.php?id=10"
 */  
  
echo $_SERVER['REQUEST_URI'];//结果:"/index.php?id=10"
/**
 *Question 50: How to implement bidirectional queue using php?
 */  
class  
    public $queue;  
    public function __construct(){//Constructor, create an array  
        $this->queue = array();  
    }  
  
    public function addFirst($item){//array_unshift() The function inserts one or more elements at the beginning of the array.  
        return array_unshift($this->queue , $item);  
    }  
  
    public function removeFirst(){  
        return array_shift($this->queue);//PHP array_shift() function deletes the first element in the array  
    }  
  
    public function addLast($item){//Add an element to the end of the array, no subscript is specified, the default is a number  
        return array_push($this->queue , $item);  
    }  
  
    public function removeLast(){  
        return array_pop($this->queue);//PHP array_pop() function deletes the last element in the array  
    }  
}  
//Question 51: Count the number of occurrences of all values ​​in a one-dimensional array? Returns an array whose key name is the value of the original array; the key value is the number of times the value appears in the original array  
$array=array(4,5,1,2,3,1,2,"a","a");  
  
$ac=array_count_values($array);  
  
/**
 * output result:
 * Array(
 *   [4] => 1
 *   [5] => 1
 *   [1] => 2
 *   [2] => 2
 *   [3] => 1
 *   [a] => 2
 * )
 */  
echo "<pre>";print_r($ac);  
//Question 53: Does the str_word_count() function count the number of words in a string?  
  
/**
 * output result: 2
 */  
echo str_word_count("Hello world!");//Parameter 2: default 0, the number of returned words  
  
/**
 * output result:
   Array(
    [0] => Hello
    [1] => world
   )
 */  
echo "<pre>";print_r(str_word_count("Hello world!",1));//parameter two: 1 - return an array containing the words in the string  
  
/**
 * output result:
   Array(
    [0] => Hello
    [6] => world
   )
 */  
echo "<pre>";print_r(str_word_count("Hello world!",2));//Parameter 2: 2- Returns an array, where the key is the position of the word in the string, and the value is the actual word .
/**
 * Question 56: What is the difference between redis and memcached?
 *
 * difference:
 *
 * (1) Not all data in redis can only be resident in memory during the validity period (if necessary, it can be periodically persisted to disk synchronously), which is the biggest difference compared to memcached (the data in memcached is within the validity period) are resident in memory in the form of key-value pairs)
 * (2) redis not only supports simple key-value pair type data, but also provides storage of data structures such as list, set, hash, etc.; memcached only supports simple key-value pair type data, but memcached can cache pictures, video, etc.
 * (3) Redis supports data backup, that is, data backup in master-slave mode
 * (4) Redis supports data persistence and data synchronization. It can save the data in memory on the disk, and can be loaded and used again after restarting the system. The cached data will not be lost because of this. The memached cached data is resident in memory , after restarting the system, the data is gone
 * (5) Redis can set the validity period through expire, and memcached can specify that the data to be cached will never expire when setting data
 * (6) redis can be one master and multiple slaves; memcached can also be one master and multiple slaves
 * (7) When redis runs out of physical memory, it can exchange some values ​​that have not been used for a long time to disk; memcached will automatically clean up some early data when physical memory runs out
 *
 * Same point:
 *
 * (1) Both redis and memcached store data in memory, both are in-memory databases
 * (2) Both redis and memcached can be one master and multiple slaves
 *
 * Performance:
 *
 * (1) According to its official test results, redis requests 10w times in the case of 50 concurrency, the write speed is 110,000 times/s, and the read speed is 81,000 times/s
 * (2) Redis sets the maximum upper limit of the key name and value to 512MB; for memcached, <span id="transmark"></span> limits the key name to 250 bytes and the value to no more than 1MB. , and only applies to ordinary strings.
 *
 * When to use memcached:
 *
 * (1) Small static data: When we need to cache small static data, we can consider memcached, the most representative example is the HTML code fragment; because the internal memory management mechanism of memcached is not as complicated as that of redis, but it is more It is practically efficient because memcached consumes relatively less memory resources when processing metadata. As the only data type supported by memcached, strings are very suitable for storing data that only needs to be read. , because the string itself needs no further processing <span id="transmark"></span>.
 *
 */

//Question 58: Use cases for file caching  
public function &get($key, $cache_time = '') {  
        if(empty ($cache_time)) {  
            $cache_time = $this->cache_time;//Cache time  
        } else {  
            $cache_time = intval($cache_time);//Cache time  
        }  
        $cache_encode_key = $this->get_key($key);//Get a unique long string  
                //The name of the cache file and the storage location of the cache file  
        $filename = $this->cache_dir.'/'.substr($cache_encode_key,0,2).'/'.substr($cache_encode_key,2,2).'/'.$cache_encode_key.".cache.php";  
        if(!is_file($filename) || time() - filemtime($filename) > $cache_time) {//If the cache file does not exist or the cache file expires, return false  
            return false;  
        } else {  
            return unserialize(file_get_contents($filename));//If the cached file exists and has not expired, then read the cached file content and return  
        }  
    }  
    public function set($key,$data) {  
        $cache_encode_key  = $this->get_key($key);  
        $cache_dir = $this->cache_dir.'/'.substr($cache_encode_key,0,2).'/'.substr($cache_encode_key,2,2).'/';//Cache directory of cached files  
        $filename = $cache_dir.$cache_encode_key.".cache.php";//Cache file name  
        if( $this->mkpath($cache_dir) ) {//Create a cache directory recursively  
            $out = serialize($data);//Serialize the data to be cached  
            file_put_contents($filename, $out);//Write the serialized data to the cache file  
        }  
    }  
    public function add($key, $data) {  
        $cache_encode_key   = $this->get_key($key);  
        $cache_dir  = $this->cache_dir.'/'.substr($cache_encode_key,0,2).'/'.substr($cache_encode_key,2,2).'/';//缓存目录  
        $filename = $cache_dir.$cache_encode_key.".cache.php";//Cache file name  
        if(is_file($filename)) {//If the cache file exists, return false  
            return false;  
        } else {//If the cache file does not exist, generate a new cache file to the cache directory  
            $this->set($key, $data);  
        }  
    }  
    public function del($key) {  
        $cache_encode_key   = $this->get_key($key);  
        $cache_dir  = $this->cache_dir.'/'.substr($cache_encode_key,0,2).'/'.substr($cache_encode_key,2,2).'/';//缓存目录<span id="transmark"></span>  
        $filename = $cache_dir.$cache_encode_key.".cache.php";//Cache file name  
        if(is_file($filename)) {//If the cache file exists, return false<span id="transmark"></span>  
            return false;  
        } else {//If the cache file does not exist, delete the cache file  
            @unlink($filename);  
        }  
    }  
  
        public function get_key($key){  
                return md5(CACHE_KEY.$key);//md5 encrypted string  
        }  

//Question 60: How does php read the value of configuration options in the php.ini configuration file  
echo ini_get('post_max_size');//Get the maximum size of the uploaded file  
echo get_cfg_var('post_max_size');//Get the maximum size of the uploaded file  

/**
 *Question 62: __call is a magic method
 * __call is the magic method, which refers to the processing method used when the requested method does not exist; if the requested method name exists (not related to the parameter list), this magic method will not be called
 */  
class MethodTest {  
     /**
      * Another example:
      * public function __call($funName, $args){//parameter 1 - the method name to be called parameter 2 - the parameter list passed to the method to be called
      *             switch (count($args)) {
      *                 case 0:
      *                     return $this->$funName();
      *                 case 1:
      *                     return $this->$funName($args[0]);
      *                 case 2:
      *                     return $this->$funName($args[0], $args[1]);
      *                 case 3:
      *                     return $this->$funName($args[0], $args[1], $args[2]);
      *                 case 4:
      *                     return $this->$funName($args[0], $args[1], $args[2], $args[3]);
      *                 case 5:
      *                     return $this->$funName($args[0], $args[1], $args[2], $args[3], $args[4]);
      *                 default:
      *                     return call_user_func_array($this->$funName, $args);
      *             }
      *     }
      */  
     public function __call($name,$arguments) {//parameter 1 - the method name of the call parameter 2 - the parameter list passed to the calling method  
        if(method_exists($this,$name)){  
            return $this->$name();  
        }else{    
            echo "The called method $name() does not exist; the parameter list passed to the $name() method is as follows: ".implode(',',$arguments)."\n";  
        }  
     }  
}  
$obj = new MethodTest();  
//Result: The called method runTest() does not exist; the parameter list passed to the runTest() method is as follows: Li Si, Zhang San   
$obj->runTest('Li Si','Zhang San');//Method name, parameter column
/**  
 * Question 65: Rewriting and overloading in php
 * Let's first understand two concepts:
 * Override/Override: It means that the subclass has rewritten the method of the same name of the parent class, but the number and type of parameters of the overridden method of the same name are not limited <span id="transmark"></span> occurs in the subclass and the between parent classes  
 * Overloading: means that there are multiple methods with the same name in this class, but the parameter types/numbers are different. When different parameters are passed, different methods are called inside this class.  
 * In PHP, multiple methods with the same name are not allowed. Therefore, such overloading in java and c++ cannot be completed; however, PHP is flexible and can simulate similar effects  
*/  
  
class human{  
      public function say($name){  
            echo $name,'Have you eaten?<br />';  
      }  
}  
  
class stu extends human{  
  
      /*
       * Error: Fatal error: Cannot redeclare stu::say() in D:\wamp\www\php\61.php on line 28, because in PHP, multiple methods with the same name are not allowed, and there is no overloading concept. Say.
       * public function say($a,$b,$c){
       * echo 'Hello, brother three';
       * }
      */  
      public function say(){  
            echo 'Cheke trouble, card cat Baibi<br />';  
      }  
        
}  
  
$ li = new stu ();  
$li->say();//Result: Checker trouble, card cat hundred ratio;  
$li->say('binghui');//Result: Checker trouble, Kamao Baibi; the above process is called rewriting  
  
  
  
// Simulate overloaded methods in PHP  
class Calc {   
    public function area() {   
        / / Determine the number of parameters obtained when a call area is called   
        $args = func_get_args();//Get the number of parameters   
        if(count($args) == 1) {   
            return 3.14 * $args[0] * $args[0];   
        } else if(count($args) == 2) {   
            return $args[0] * $args[1];   
        } else {   
            return 'Unknown figure';   
        }   
    }   
}   
$ calc = new Calc ();   
// Calculate the page of the circle   
echo $calc->area(10),'<br />';   
// Calculate the area of ​​the rectangle   
echo $calc->area(5,8);















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441106&siteId=291194637