简体   繁体   中英

Correct Usage of Classes in CakePHP 3.x

Trying to use $url = Router::url(...); as per the book ( http://book.cakephp.org/3.0/en/development/routing.html#generating-urls ) and I can get it to work by adding use Cake\\Routing\\Router; to my controller but I have a feeling that there has to be an easier/better way than that and I recall someone mentioning to never call a function by Class::function() .

Through further research (never stop looking) it appears that it's just a Class thing.

  1. Load Class with use Cake\\Routing\\Router;
  2. Instantiate the Class with $routes = new Router();
  3. Use the Class instance to call the function $url = $routes->url(...);

To use a static(?) function of a Class is it really better to instantiate the Class or just use Router::url()?

To use a static(?) function of a Class is it really better to instantiate the Class or just use Router::url()?

url() is a public static method of the class Router. The correct way to call that in PHP is Router::url(...) (using the scope resolution operator, ::).

I recall someone mentioning to never call a function by Class::function().

If you can find it, I'd be interested to hear his or her reasoning.

If he or she meant that the scope resolution operator is not the best way to access a static method, he or she is mistaken. As far as PHP man is concerned, the scope resolution operator is the correct way to access a public static method from outside the class context: Scope Resolution Operator .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM