2
\$\begingroup\$

I'm currently working on a PHP component: "Filesystem handler". I've run into a problem where I want to call one exact method in both dynamic and static ways.

I've ended up with this solution. Could you please give me a feedback ? I want to know, if there is a better or a simpler way to achieve the same result.

<?php

class File {

protected $file;

public function __construct($file) {
    $this->file = $file;
}

protected static function exists($arg) {
    var_dump($arg);
}

public function __call($method, $parameters = null) {
    if($method == 'exists') {
        return call_user_func_array(array($this, 'exists'), array(array($this->file)));
    }
}

public static function __callStatic($method, $parameters) {
    if($method == 'exists') {
        return call_user_func(__CLASS__.'::exists', $parameters);
    }
}

}

$file = new File('dynamic');
$file->exists();

File::exists('static');
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The first thing you should now is that magic methods are slow __call and __callStatic, that is. The second thing I'd like to point out is that, given that you declared the method as static, you should always call it as such. Failing to do so is just going to leave you with code that is a nightmare to maintain: every call to every function will need to be checked and double checked, just to know if that method is indeed static or not.

Lastly: why aren't you simply calling the method statically on your instance?

$file = new File('dynamic');
$file::exists();

That'll work just fine, too. But all in all: a method should be either static (which isn't that useful in PHP 9/10 times anyway) or not. Trying to allow for static calls aswell as instance calls means you are writing a class that offers a messy API. Don't

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.