Jump to content

Creating object only once in a function


Go to solution Solved by kicken,

Recommended Posts

The following is a global logging function.  It is used on a PHP service than runs indefinitely, so I don't want to needlessly use memory.

<?php

// Debug Message
if(!function_exists('dm'))
{
    function dm($msg)
    {
        if(getenv('DEBUG')) {
            $time = date('Y-m-d H:i:s', time());
            switch (gettype($msg)) {
                case 'string':
                    echo $time . ' ' . $msg . PHP_EOL;
                    break;
                case 'array':
                    echo $time . ' ';
                    print_r($msg);
                    break;
                
                default:
                    echo $time . ' ';
                    var_dump($msg);
                    break;
            }
        }
    }
}

  I next wish to add a Monolog to it, and log all times dm() is called.  How should I do so so that the $logger object is not created each time, and also without polluting namespace?

$logger = new \Monolog\Logger('my_logger');
$logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__."/../logs/client.log"));
$logger->addInfo('hello');

Humm, as I write this, I wonder if this is a good use of the static keyword?

Link to comment
https://forums.phpfreaks.com/topic/302525-creating-object-only-once-in-a-function/
Share on other sites

Testing my theory, but no-go...  Any other suggestions?  EDIT. Also, why the error?

<?php

// Debug Message
if(!function_exists('dm'))
{
    function dm($msg)
    {
        if(getenv('DEBUG')) {
            $time = date('Y-m-d H:i:s', time());
            switch (gettype($msg)) {
                case 'string':
                    echo $time . ' ' . $msg . PHP_EOL;
                    break;
                case 'array':
                    echo $time . ' ';
                    print_r($msg);
                    break;

                default:
                    echo $time . ' ';
                    var_dump($msg);
                    break;
            }
        }
        if(!isset($logger)) {
            static $logger = new \Monolog\Logger('my_logger');
            $this->logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__."/../logs/client.log"));
        }
        $logger->addInfo('Hello');
    }
}
michael@dev2:/var/www $ php client.php
PHP Parse error:  syntax error, unexpected 'new' (T_NEW) in /var/www/src/Support/helpers.php on line 26
michael@dev2:/var/www $
Edited by NotionCommotion

Is this in an object or function sheet? I don't see a scope definition on the function, but you use $this->logger->pushHandler(...) after creating a static $logger instance (no $this reference), which I'm not sure makes a lot of sense to begin with. I could be wrong on that last bit, though - it's been a long week...

Thanks maxxd,

 

dm() is a function, and $logger is an object.

 

The $this->logger->pushHandler(...) was a typo and I meant $logger->pushHandler(...).  That wasn't the error, however, but the error was making the object static.  Probably a bad design pattern, but still would like to know why it results in the error, and what other approaches there are..

  • Solution

You can only initialize a static variable to a constant value. Initialize it to null then check in the function if it's null and if so create the object.

 

function dm(){
    static $logger = null;
    if($logger == null){
        $logger = new \Monolog\Logger('my_logger');
        $logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__."/../logs/client.log"));
    }

    $logger->addInfo('Hello');
}

How about The static keyword

Note:

Static declarations are resolved in compile-time. 

[...]

From PHP 5.6 you can assign values to these variables which are the result of expressions, but you can't use any function here, what will cause a parse error.

It took me 10 seconds to find that. If you're less experienced with Google or the structure of the manual, it might take you 30 seconds.

 

My point is that you need to learn how to do your own research.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.