search
HomeBackend DevelopmentPHP TutorialClever overloading of the magic method __call()

I have been working for half a year, and I feel that I have learned more in this half year than in four years of college. The main reason is that my mind has calmed down, my goals are clear, and I will not be entangled with games all day long. When I was in college, I actually realized that playing games would affect my normal study and work, but I couldn't control myself. I still couldn't help but play often, day and night (I was originally a sultry guy, and I still stayed at home playing games. , this is also one of the reasons why I only had games, left and right hands, and no girlfriends during the four years of college). Now that I am working, I have tasks every day. When I see the talented people next to me working on the project like a duck to water, I have the idea of ​​catching up with them, so I give myself an extra small task every day to learn new knowledge. I have been working for half a year now. Now I can use Linux which I was not familiar with before. I also have a new understanding of JS which I am not familiar with. It can be said that I am competent at the job now (if divided into novice, advanced novice, competent and proficient) , experts), have developed activities, interfaces, and backends, and have also optimized and improved the system framework. As long as there are reasonable needs raised by product operations, they can be quickly supported. Of course, I really feel one thing: Programmers are really a strange group. Most of the time, they always think that their own ideas are the best. Of course, this is considered self-confidence, but sometimes your aggressiveness during discussions is not necessarily a good thing, so you should listen to other people's ideas. Not only can you discover your own shortcomings, but you can also build a good "friendship". I’ve been telling you so much about my feelings over the past six months, thank you for sticking with me and reading it^_^.

Let’s step into the real question and talk about how to skillfully use the magic method of PHP. I believe this will be used in most projects.

First of all, I would like to explain that this little trick has been used very well in my project, and it has brought great convenience to our project. I will give you some details here, you may wish to continue reading.

In the project, there must be a large amount of configuration information that can be configured, such as the robot opening time period of a game, whether the payment method is enabled, the configuration of the title display in the mall, etc. One characteristic of these configuration information is that there is no specific Rules, and product operations can be modified at any time according to the actual situation. How to save this information? It is definitely not possible to build a table for each type. Doing so is simply thankless. If you think about it, maybe one table can A piece of information is saved, so I have to think of other methods. Although there are no rules for this information, one of their characteristics is that there will not be too much, and generally an array can save all the information that needs to be configured, so json characters are used String storage information is a good choice. When you need to use it, just take out the json_decode and you can use it directly. Let’s take a look at how to cleverly use PHP’s magic method to achieve it.

Here you first need to understand __call(), a magic method of PHP. Check the official PHP documentation, which explains this function like this

<span>public</span> <span>mixed</span> __call ( <span>string</span> <span>$name</span> , <span>array</span> <span>$arguments</span><span> )

__call() is triggered when invoking inaccessible methods in an </span><span>object</span> context.

It means that this function will be triggered when an inaccessible method (no permission, non-existence) is called in an object. The parameter $name of the function is the name of the called function, and $arguments is the parameter array of the called function. Take a look at this example:

<span>class</span><span> Test
{
    </span><span>public</span> <span>function</span> __call(<span>$name</span>, <span>$arguments</span><span>)
    {
        </span><span>echo</span> "你调用了一个不存在的方法:\r"<span>;
        </span><span>echo</span> "函数名:{<span>$name</span>}\r"<span>;
        </span><span>echo</span> "参数: \r"<span>;
        </span><span>print_r</span>(<span>$arguments</span><span>);
    }
}

</span><span>$T</span> = <span>new</span><span> Test();
</span><span>$T</span>->setrobottime("12", "18");

This function will output the following results

<span>你调用了一个不存在的方法:
函数名:setrobottime
参数: 
Array
(
    [</span>0] => 12<span>
    [</span>1] => 18<span>
)</span>

In this way, we can not define the function directly, but use this feature to do something. Let’s take a look at the implementation ideas of the code, mainly the ideas, some of which I have made assumptions about, such as database connections, which I won’t focus on here.

<span>class</span><span> Config
{
    </span><span>/*</span><span>*
     * 这里假定下数据库表名为
     * config.config,
     * 字段为:
     * config_key varchar(50),
     * config_value text,
     * primary key(config_key)
     *
     * 数据库连接为$link
     * 插入方法封装为query
     * 获取一条信息方法封装为getOne
     </span><span>*/</span>
    <span>/*</span><span>*
     * 要进行的操作
     </span><span>*/</span>
    <span>private</span> <span>static</span> <span>$keys</span> = <span>array</span><span>(
        </span><span>//</span><span>'调用方法' => 'key',</span>
        'roboottime'    => 'ROBOOTTIME',
        'dailysignin'   => 'DAILYSIGNIN',<span>
    );

    </span><span>/*</span><span>*
     * 设置方法
     * @param string $config_key 配置项key
     * @param string $config_value 配置型内容(一般为json格式)
     * @returne boolen true/false 插入是否成功
     </span><span>*/</span>
    <span>private</span> <span>function</span> set(<span>$config_key</span>, <span>$config_value</span><span>){
        </span><span>$sql</span> = "insert into config.config (config_key,config_value) values ('{<span>$config_key</span>}','{<span>$config_value</span>}') on duplicate key update config_value='{<span>$config_value</span>}'"<span>;
        </span><span>return</span> <span>$link</span>->query(<span>$sql</span><span>);
    }

    </span><span>/*</span><span>*
     * 获取值的方法
     * @param $config_key 要获取的配置的key
     * @returne string/false json字符串/失败
     </span><span>*/</span>
    <span>private</span> <span>function</span> get(<span>$config_key</span><span>)
    {
        </span><span>$sql</span> = "select * from config.config where config_key='{<span>$config_key</span>}'"<span>;
        </span><span>if</span>(<span>$ret</span> = <span>$link</span>->getOne(<span>$sql</span>,<span> MYSQL_ASSOC)){
            </span><span>return</span> <span>$ret</span><span>;
        }
        </span><span>return</span> <span>false</span><span>;
    }

    </span><span>/*</span><span>*
     * 重载魔术方法
     * @param string $name 被调用的方法名
     * @param array $arguments 调用时传递的参数
     * @return mixed 返回结果
     </span><span>*/</span>
    <span>public</span> <span>function</span> __call(<span>$name</span>, <span>$arguments</span><span>)
    {
        </span><span>$act</span>    = <span>substr</span>(<span>$name</span>, 0, 3<span>);
        </span><span>$func</span>   = <span>substr</span>(<span>$name</span>, 3<span>);
        </span><span>if</span>(!<span>in_array</span>(<span>$func</span>, self::<span>$keys</span><span>)){
            </span><span>return</span> <span>false</span><span>;
        }
        </span><span>if</span>(<span>$act</span> == 'set'<span>)
        {
            </span><span>return</span> <span>$this</span>->set(self::[<span>$func</span>], <span>$arguments</span>[0<span>]);
        }
        </span><span>elseif</span>(<span>$act</span> == 'get'<span>)
        {
            </span><span>return</span> <span>$this</span>->get(self::[<span>$func</span><span>]);
        }
        </span><span>return</span> <span>false</span><span>;
    }
}</span>

In this way, we can store multiple information through one table, and it is very convenient when calling. We only need to expand the information in the Config::$keys array. This is just for standardization and clarity. Know which configurations are stored in this table.

You can store and retrieve it like this when using it

<span>$config</span> = <span>new</span><span> Config();

</span><span>$info</span> = <span>array</span>("12","20"<span>);

</span><span>//</span><span>设置</span>
<span>$config</span>->setroboottime(json_encode(<span>$info</span><span>));

</span><span>//</span><span>获取</span>
<span>$config</span>->getroboottime();

Another point to note here is that these configuration information will generally be cached in redis and placed in the database just to prevent recovery from the database after redis hangs. This generally refers to information that is frequently read. In order to reduce the interaction with the db, place it directly in the cache.

 The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author's consent. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved. .

posted @ 2015-01-10 12:23 Running Man Read (...) Comment (...) Edit Collection

Refresh comments Refresh page Return to top

Blog Park Homepage Bowen News Flash Programmer Recruitment Knowledge Base

公告

Copyright ©2015 奔跑的Man

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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version