Home  >  Article  >  Backend Development  >  [Happy 100 days of learning PHP] Day 4: Complete the PHP magic function_PHP tutorial

[Happy 100 days of learning PHP] Day 4: Complete the PHP magic function_PHP tutorial

WBOY
WBOYOriginal
2016-07-14 10:09:56862browse

Motto for this issue:

When our talents are not strong enough, instead of spending 500% of the energy to be a single-threaded technical master, it is better to spend less energy to be a smart multi-threaded programmer.
Bullshit in this issue:
The first season of Hunan Satellite TV's "I Am a Singer" has ended, and the king of singers has emerged. Maybe many people have different ideas of the King of Singer, but it is undeniable that Yu Quan has indeed been "officially" announced and "recognized by everyone" as the King of Singer. My personal analysis is as follows:
In fact, all singers are very strong and have their own characteristics. There is really no such thing as a king of singers. For example, Lin Zhixuan, who has been gifted by God, soprano Huang Ma, Zhou Xiaoou, who is rocking all over, Yang Zongwei, who is extremely delicate, and other singers with their own characteristics. But I personally think that only Yu Quan is the smartest singer. In terms of timbre, he may not be as good as Lin Zhixuan, in terms of touching, he may not be as good as Yang Zongwei, in terms of high notes, he is not as high as his mother, and in terms of rock music, he has to shave his head, so Yu Quan’s strategy is to integrate himself into the audience, and Not forcing the audience into their songs. Finally, he came up with the most powerful weapon in the winning game.
Here I will also write a god-level analysis that I have processed: When voting for Yu Quan, there is one vote for liking "Yu", one vote for liking "Quan", one vote for liking Deng Chao, one vote for liking Sun Li, and one vote for liking Bai Baihe. , there is a vote for supporting 3G Tianyi, and there is a vote for those who are using Liby laundry detergent at home. Therefore, it is unforgivable that Yuquan did not get the first place in the vote. What’s more, Liby and Tianyi are also sponsors of this program.
The same goes for programmers: when we suddenly debuted, we found that there were too many Java masters and seniors, and it was difficult to catch up with them naked. After all, their development experience was put there; then we discovered c#, this version and functions Upgrading is too fast, and it is difficult to master everything and become an expert even if you learn it naked; look at python or ruby ​​again, people who learn well are definitely experts and are in the minority, and people who do not learn well are basically shit; therefore we It is better to learn PHP, because there is one vote for those who like Taobao, one vote for those who like MySQL, one vote for those who like Apache, one vote for those who like WordPress, one vote for those who like DZ Forum, and one vote for those who like CentOS. I won’t say more, Yu Quan is the song King, why don’t we find a way to become the king of programmers.
Text: Magic function
Why is it called the magic function? It may be called the magic function in some places. The reason is simple. No other language allows you to learn it from beginning to end, from inside to out, so conveniently and simply. After you finish it, you will feel like you have completely conquered PHP. This feeling is difficult to find in java, what about c#? Oh, there’s no need to talk about it.
(1), __construct constructor
The constructor function means that it is the first function to be exploded. Regardless of whether you want to explode it or not, it will explode automatically anyway.
[php]
class test
{
function __construct()
                                                                 
Echo 'The first time I exploded';
      }  
function mydo()
                                                         
Echo 'Manually explode';
                                                          
}
$newObj = new test();
$newObj->mydo();
The result of the operation is that it will self-destruct for the first time (whether you want it or not), and then it will explode for the second time.
A knowledge point here is: passing parameters is also very simple, you can __construct($arg1,$arg2);
Similarly, you can also use the func_get_args function to get an unknown number of parameters. For example
[php]
class test
{
function __construct()
                                                                 
$getargs=func_get_args();
if(count($getargs)<2)
                  exit("There must be two parameters");  
      }  
function mydo()
                                                         
echo "manually";
                                                          
}
$newObj = new test("aaa"); //The value of $getargs[0] in the constructor is aaa
$newObj->mydo();
Note that if exit is used, the mydo method will not run, which means that it is impossible for you to explode manually. Similar to c#'s response.end.
Most of the usage of this constructor is used in class inheritance, and it can also be used directly in page output content to load different content according to the number of parameters.
(2), __destruct() destructor
The principle explanation of the destructor is: when an object is deleted or the object operation terminates, this method is automatically called, so operations such as releasing resources can be performed.
Actually, let’s not think too much. If we use php, we don’t need to pay attention to this function at all. Zend is responsible for all resource release, and PHP is not suitable for doing large data super loops in classes, otherwise it will really explode. Generally, in actual projects, some small things such as log recording will be done through inheritance. If there are millions of data to be processed in your class, it either means that you have received a big project and you are about to publish it, or you are dreaming.
(3), __autoload automatic loading
This function is only useful in one place. It is to automatically load the function file.
[php]
class fruit
{
function __construct($user’s choice)
                                                                 
                                                                                                                                                                                                               
$ Apple's object = new apple (); // Here it will automatically load a function required by 啃 Apple .php
          else  
                                                                                                                                                                                                       ’                 ’ ’ s ’ ’ t       out down     ‐ out through  through       ‐                                
      }  
}
class Durian
{
//Too smelly, but I like to eat it
}
class apple
{
//It doesn’t stink, but I don’t like to eat it
function __autoload()
                                                                       
require("Function required by Apple.php");
      }  
}
$newObj = new fruit(1);
Please do not copy and run the above examples directly. They are written in Chinese to make them easier to understand.
(4), __call
When calling a function of a non-existent class, you need to handle the method. If __call fails, the parent class method is called, and so on.
Personally, I think this function is the most powerful function in PHP. From this you can write very bright code, for example:
[php]
class data
{
function __call($name,$arguments)
{
//$name represents the method name $arguments represents the parameters
if($name=="getSqlServer")
{
// Execute sql statements related to sqlserver
} }
else
{
//Execute mysql related sql statements
} }
}
}
$newObj = new data();
$newObj->getSqlServer("select top 10 * from table1"); //getSqlserver This method does not need to be pre-defined
$newObj->getMysql("select * from table1 limit 0,10");//Note that mysql does not have top n syntax
Of course, the above is an example. You can draw inferences from one example. It can be used in both the data layer and the business layer. Especially when building a virtual entity or virtual class, it can achieve highly configurable code writing.
(5), __get, __set
When the attribute is undefined, it will be automatically called when getting or setting.
[php]
class data
{
function __get($name) //$name represents the attribute name
{
if($name=="H7N9") //If the variable is H7N9 and it is not defined, __get is called. If it is defined, it will not enter
return "bird flu";
else
return "Don't talk nonsense";
}
}
$newObj = new data();
echo $newObj->H7N9;
echo $newObj->H100N30;
Using this method, you can still write bright code
(6), __clone()
Function executed when the object is cloned
[php]
class data
{
var $myname="shenyisyn";
function __clone()
{
$this->myname="fake shenyisyn";
}
}
$newObj = new data();
echo $newObj->myname;
$obj2=clone $newObj;
echo $obj2->myname;
This function is also found in actual projects. For example, if you are building a news website, the class of a certain news is called news. Users may copy the same news for collection. At this time, we can use the __clone() function to set certain identifiers. value is processed. Such as
[php]
class news
{
var $newsid=1;
function __clone()
{
//Execute the news with ID 1 in the database, let it be quoted or add +1 to the collection field
}
}
$newObj = new news();
$news2=clone $newObj;//Finally, an external site user came to collect news from our site, I am so happy
(7),__toString()
The usage is straightforward with examples
[php]
class news
{
var $newstitle="US Secretary of State Kerry arrives in Beijing for a visit to China";
function __toString() //If you don’t add this function, the object cannot be output as a string.
{
return "This is a news object, I can only give you a title";
}
}
$newObj = new news();
echo $newObj; //Um. . I made a mistake and forgot that this item is not a string, but it can still be exploded
(8), __sleep, __wakeup
This function is only automatically called when the class is serialized or deserialized. Look
[php]
class news
{
var $user1="彞工";
var $user2="Pig Ganglie";
var $user3="Senior";
function __sleep()
{
echo "Senior sister is confidential and will not let you serialize";
Return array("user1","user2");//user1 and user2 must be consistent with the variable names defined above.
}
}
$newObj = new news();
$obj=serialize($newObj);
var_dump($obj);
The above is the magic function of php. In fact, this is one of the brightest parts of php.
To write a very manly and sexy program in later actual projects, you must first understand these magic functions.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477562.htmlTechArticleThis issue’s motto: When our talent is not strong enough, instead of spending 500% of our energy to be a single-threaded technical master, It's better to spend less energy being a smart multi-threaded programmer. Nonsense in this issue:...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn