Monday, September 30, 2019

PHP Magic method: __call


Function Definition: https://www.php.net/manual/en/language.oop5.overloading.php#object.call

Recently during tracing some PHP library, I saw some interesting ways to use this PHP magic method. The library is built for finding the appropriate phtml and then sending it back to front-end to be displayed. I will write some similar, but simple code to this note to demonstrate it.


Demonstration:

1. Provide two phtml files in the same folder



2. Paste the following code to template.php file.

<?php

class Template
{
    public function __call($name, $arguments)
    {
        $output = '';
        $file = './'. $name . '.phtml';
        if ($file != NULL && file_exists($file)) {
            $output = file_get_contents($file, true);
        }else {
            $output = 'Template not found!\n';
        }
        return $output;
    }
}

$template = new Template;
echo $template->myheader();
echo $template->myfooter();

3. The result will be shown as following after executing template.php.




Summary:

From previous code, because myheader() and myfooter() functions do not exist in template.php, therefore the magic function “__call” will be triggered. Inside “__call” function, we could add some conditions or pass the file path information to make this “template finding library” more flexible. However, in order to make it simple for demonstrating, we only read file content from the generated file name, which is generated by "called function name". 

This usage of this magic function is quiet interesting. That is why I think it is worthy to take this note.

1 comment:

  1. Hi Frank,

    Hope you are doing well, I like your blogs and I have opportunity with Amazon Vancouver, If you are interested Please send me email gilnavde@amazon.com.

    Regards,
    Navdeep Gill

    ReplyDelete