Ingenious heavy-duty Magic Method __call (), heavy-duty Magic __call_php Tutorial

Source: Internet
Author: User

Ingenious heavy-duty Magic Method __call (), heavy-duty magic __call


Work for half a year, feel this half-year learned more than the university four years of learning more, the main reason is calm down, the goal is clear, will not go all day and the game entangled together. College when in fact also realized that playing games will affect their normal study and work, but have been unable to control themselves, or can not help often to play, Day and night play (originally is stuffy Sao male, also curtilage play game, this is the university four years only game, right hand, no girlfriend of a reason). Now work, every day have a task, see next to the cow people in the project, there is the idea of catching up with them, so every day will give himself an extra small task to learn new knowledge, to now work for half a year, to the formerly unfamiliar Linux can now also be familiar with the use of To unfamiliar JS also has a new understanding, can say now I can be competent for the job (if divided into novice, senior novice, competent, proficient, expert), has developed activities, interfaces, backstage, but also optimize the framework of the system, as long as the product operation of reasonable demand can be quickly supported in place. It is true that programmers are really a strange group, and most of the time they always think their ideas are the best. Of course, this is self-confidence, but sometimes the discussion of your aggression is not necessarily a good thing, so also listen to other people's ideas, not only can find their shortcomings, but also to establish a good: "Friendship." With everyone to talk about so much of this half a little feeling, thank you can insist on reading ^_^.

The following step into the real topic, said how to skillfully use the Magic method of PHP, I believe this will be used in most projects.

First of all, this little trick I have in the project has a very good application, to our project has brought great convenience, here first sell Xiaoguanzi, you may wish to continue to look down.

In the project, can be equipped with a large number of configuration information, such as a game of robot open time, payment method open or not, the mall display title configuration, etc., these configuration information generally have a feature is no specific rules, and product operations can be at any time to the actual situation to modify, How to save this information, certainly not each type to build a table, this is simply thankless, you think, perhaps a table saved a piece of information, so you have to think of other methods, although the information is not rules, but they have a feature is not too much, And in general, the array can save all the information that needs to be configured, so storing information with JSON string is a good choice, when need to use the direct removal of json_decode so that you can directly use, the following to see how the clever use of PHP magic method to achieve.

Here you have to understand the next PHP Magic Method __call (), check the official PHP document, this explains the function of the

 Public Mixed string $name Array $arguments  Object context.

This means that when a non-accessible method is invoked in an object (no permission, no presence), the function is called, and the function's argument $name is the calling function name, $arguments is an array of functions arguments called. Take a look at the following example:

class test{    publicfunction __call ($name$arguments)    {         echo "You called a non-existent method: \ r";         Echo "Function name: {$name}\r";         Echo "parameter: \ r"        ; Print_r ($arguments);}    } $T New Test (); $T->setrobottime ("12", "18");

This function will output the following result

you call a nonexistent method: function name: setrobottime parameter: Array (    [0] =    [1] = +)

In this way, we can not directly define the function, but use this feature to do something. The following look at the implementation of the Code, the main idea, some of which I am hypothetical, like a database connection, this is not the main point.

classconfig{/** * This assumes that the database table name is * config.config, * field: * Config_key varchar (+), * config_value text, * prima Ry Key (config_key) * * Database connection is $link * Insert method encapsulated as Query * Gets a message method encapsulated as GetOne*/    /** * The operation to be performed*/    Private Static $keys=Array(        //' call method ' = ' key ',' Roboottime ' = ' roboottime ', ' dailysignin ' = ' dailysignin ',    ); /** * Set method * @param string $config _key configuration Item Key * @param string $config _value configuration content (generally in JSON format) * @returne Boolen True/false If the insertion is successful*/    Private functionSet$config _key,$config _value){        $sql= "INSERT into Config.config (config_key,config_value) VALUES (' {$config _key}','{$config _value} ') on duplicate key update config_value= ' {$config _value}'"; return $link->query ($sql); }    /** * method to get the value * @param $config _key to get the configuration key * @returne String/false JSON string/failed*/    Private functionGet$config _key)    {        $sql= "SELECT * from Config.config where config_key= ' {$config _key}'"; if($ret=$link->getone ($sql,Mysql_assoc)) {            return $ret; }        return false; }    /** * Overloaded Magic method * @param string $name called method name * @param array $arguments arguments passed when calling * @return mixed return results */     Public function__call ($name,$arguments)    {        $act=substr($name, 0, 3); $func=substr($name, 3); if(!In_array($func, Self::$keys)){            return false; }        if($act= = ' Set ')        {            return $this->set (self::[$func],$arguments[0]); }        ElseIf($act= = ' Get ')        {            return $this->get (self::[$func]); }        return false; }}

In this way, we can store a number of information through a table, the invocation is also very convenient, only need to extend the config:: $keys the information in the array can be, this is only for the specification, in order to be able to clearly know which configuration is stored in this table.

When you use it, you can store and retrieve it like this.

$config New Config (); $info Array ("A", "a"); // Set $config->setroboottime (Json_encode ($info)); // Get $config->getroboottime ();

Here's another point to note that these configuration information is typically cached in Redis and placed in the database just to prevent Redis from being recovered from the database after it is hung up, which is generally referred to as the information that is often read, and in order to reduce the interaction with the DB, it is placed directly in the cache.

The copyright belongs to the author Iforever (luluyrt@163.com) all, without the author's consent to prohibit any form of reprint, reprinted article must be in the article page obvious location to the author and the original text connection, otherwise reserve the right to pursue legal responsibility.

http://www.bkjia.com/PHPjc/940335.html www.bkjia.com true http://www.bkjia.com/PHPjc/940335.html techarticle Clever heavy-duty magic Method __call (), heavy-duty magic __call work for half a year, I feel that this half-year learning more than the university four years, the main reason is calm down, the goal is ...

  • 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.