Search code examples
phpscope-resolution

PHP: How to create function which will be accessible with :: (double colon, scope resolution) in another classes


I´m trying to create a logging class which will be accessible in all Classes around the PHP app by

logger::log(something);

and this will add next row into my logfile (the part with inserting into file is easy for me). I saw the double colon in DIBI (database framework). It is cool, because I can use dibi::dataSource("") whereever I need. But don´t know how to do this in my application.

Right now I have something in some class (I have more similar classes in the app) like (shorted):

Class DoSomething {
  function runTests() {
    logger::log("Test started");
    // do the magic
    logger::log("It ends");
  }
}

In index.php I have something like:

// init
$app = new DoSomething;
$app->runTests();
...

And I would like to have in index.php some code, which will add the accessibility of logging function in class with "logger::log();". But don´t know how to do this. Can you please help me?

Maybe it can somehow work with "extends", but is there any easier solution? I have tried to read - https://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php but still not sure, how to do this.

Thank you.


Solution

  • The double colon allows access to static function and constants in a class.

    Change your class method to:

    static function runTests() {
    ...
    

    and then call it like this

    DoSomethin::runTests();