at 8:08 PM

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.
while as a function.
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. First time this is failure 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.
<?php
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);

KeyWord::unknownStaticMethod(1,2,3);

?>

Now calling method with the keyword..

:)

Tulis Komentar dengan akun Facebook Anda.

0 comments:

Post a Comment