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

221 Views Asked by At

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.

2

There are 2 best solutions below

3
kaczmen On BEST ANSWER

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();
0
Alexandre FERRERA On

If I understand correctly your question, what you are looking for is a static method. This kind of method would allow you to call your function without instantiating an object beforehand (using new Logger)

To do that, your function should be declared as public static. Here's an example:

public static function test()
{
    // Method implementation
}

More documentation here : php static functions