Does this code cause any memory problems?

1

Follow the original code:

class Table{
    private static $table;

    public static function draw( stdData $data ){
        self::$table = new self;
        return self::$table->_draw( $data );
    }
    ...

I made this modification below to try to circumvent a possible memory problem:

class Table{
    private static $table;

    public static function draw( stdData $data ){
        self::$table = new self;
        $html = self::$table->_draw( $data );
        unset(self::$table);
        return $html;
    ...

But it caused a problem:

Fatal error: Attempt to unset static property Table::$table in Table.php on line 8

Does the original code cause any memory problems? What would be the correct way out of the problem?

That is, does it occupy memory space unnecessarily?

The goal is to use echo Table::draw($data); at another time to print a table and that after use has nothing in memory because of that.

    
asked by anonymous 30.11.2015 / 21:09

2 answers

2

PHP is a script language. Programs run for a very short time. In general even though memory leaks are not very relevant.

The code does not have much context but I will say that probably should not be so. Usually the class should be normal and not static. If it's to be static, maybe it should not be a class. It seems like a lot of complication for nothing.

If you think the fact that the value is static is holding data in memory, the solution is simple, do not leave it static. So when the instance is no longer being used, it will be removed from memory.

You should ask why this class is static with global status . Or if this should be a class. There are even exceptions, but the basic rule is that if it has been, do not let it be static. Of course, if you know a lot what you're doing, that's fine. That does not seem to be the case. Goes simple.

I may be wrong, but this self::$table = new self; line does not seem to make any sense.

If you want to insist on trying to reduce memory consumption, assign a null to the static member:

$table = null;

When you need to do this, something is wrong with the code. I doubt you need this variable. The code does not even show where it's being used. Maybe nowhere. And if it is, it seems to be used the wrong way.

If the code is too confusing, there is something wrong with it, this is the biggest problem. If you do not understand 100% what is happening in it, it is better to do it in a way that you understand. Simplify. I would help more if I had more context.

    
30.11.2015 / 21:39
0

Just optimize bottlenecks, not where you do not need them. This code there tries to 'destroy' a piece of the class. The correct thing is to assign null to this property.

Instead of:

unset(self::$table);

change to:

self::$table = null;
    
30.11.2015 / 21:38