Using keyword as method in PHP

As we know, we can’t use keyword like if, while in common language programming as function, method or variables, neither does in PHP Programming. Last time, i agree with this condition, but when i learn about Object Oriented Programming i found a way how to make this is possible, i’ve got a trick how to make keyword as a method or function (as a variable we can do that easily) in PHP Programming.

How to do that?

In PHP Programming there a feature in OOP, as known as with magic method, with this feature we can do a “magic” in PHP. For completed information about it you can click that link.

Keyword as Function.

Based on Php Manual about keyword, we can’t use keyword as function, so if we coding like this, Php will show an error like this.

function while($var) {
    return true;
PHP Parse error:  syntax error, unexpected 'while' (T_WHILE), expecting '(' in Command line code on line 1

And, how to use it (or other keywords) as function? We can’t do that but, we can use it as a string in a variable with function create_function(). This is sample.

    $if = '';
    $if = create_function ('$var', 'return (bool)$var;');  
    var_dump ( $if(true));  

Keyword as Method.

Using keyword in method will give an error like above sample, we can use a trik like above, or we can use magic call with __call or __callStatic. this is failed example.


    class Keyword {  
        public function if ($var) {  
            return (bool)$var;  
    $key = new KeyWord();  // got error here..  
    $key->if (true);

And this is solution to do that.


    class KeyWord {  
        public function __call ($name, $argument) {  
            echo "You call $name with arguments: ". print_r ($argument, true);  
        public static function __callStatic ($name, $argument) {  
            echo "You call statically $name with argument: ". print_r ($argument, true);  
    $x = new KeyWord();  
    $x->static (1,2);  

Now calling method with the keyword..