0

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.

neologyc
  • 3
  • 4
  • https://stackoverflow.com/questions/33705976/when-should-i-use-static-methods may be worth a read. – Nigel Ren Oct 13 '19 at 19:34
  • What you're looking at is a *static* method. For all intents and purposes, it's nothing more than a normal global function. Read [How Not To Kill Your Testability Using Statics](http://kunststube.net/static/). – deceze Oct 13 '19 at 19:35

2 Answers2

0

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();
kaczmen
  • 528
  • 4
  • 12
  • OK, I just changed the code and it works with static in run.php. But when i use logger::log('something to log') in another Class/function. Than I get error: Notice: Undefined variable: logger in ....Project.php on line 26 Can I change the logger variable to global or something? – neologyc Oct 13 '19 at 19:35
  • Are you loading your `logger` class properly? You always need to `require/include` its file or configure autoloading. – kaczmen Oct 13 '19 at 19:39
  • I had an error there. Used another variable. Thank zou for help. It wokrs now! – neologyc Oct 13 '19 at 19:40
0

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