Global function vs vs static class

Let's say you have an object that is unique, and it is used by all other classes and functions ... something like $application.

How could you access this object in your functions?

  • using a global variable in each of your functions:

    global $application;
    $application->doStuff();
    
  • creating a function, for example application(), that creates an object in a static variable and returns it; then use this function wherever you need to access the object:

    application()->doStuff();
    
  • create a singleton thing, such as a static method inside the class of the object that returns a single instance, and use this method to access the object:

    Application::getInstance()->doStuff();
    
  • KingCrunch and skwee: pass the application object as an argument to each function / class where necessary

    ...
    public function __construct(Application $app, ...){
      ....
    

, . , / " ".

+5
3

. .

function doFoo(Application $app) {
    $app->doStuff();
}

, singleton , . , singleton, "" :

, ,

"" 3 , singleton. , . , , - Context

class Context {
    public $application;
    public $logger;
    ....
}
========
$context = new Context();
$context->application = new Application();
$context->logger = new Logger(...);
doFoo($context);
========
function doFoo(Context $context) {
    $context->application->doStuff();
    $context->logger->logThings();
}

( /, , ..).

!

+4

, , .. - -, : . application factory (, , new, , ).

, application, , . , application. .

, , php ( , , faux static class). , .

+4

, . , 2 3 .

: : " , ", , , , / .

+1

All Articles