开发者

destroy object in php

I am executing a program in PHP and getting the below error sometimes.Is this due to creating lot's of objects and not destroying them or any other reason?

Allowed memory size of 16777216 bytes exhausted (tried to allocate 19456 bytes) What is the correct method to destroy an object in PHP5.

Some code:

App::import('Vendor','GoogleShipping',array('file'=>'googlecheckout'.DS.'library'.DS.'googleshipping.php'));
App::import('Vendor','GoogleTax',array('file'=>'googlecheckout'.DS.'library'.DS.'googletax.php'));
class Cart{
    var $_itemname;
    var $_unit_price;
    public function Usecase($itemname,$unit_price,$url,$merchant_private_item_data)
    {
            $cart = new开发者_如何学编程 GoogleCart($this->_merchant_id, $this->_merchant_key, $this->_server_type,$this->_currency);
            $item_1 = new GoogleItem($this->_itemname,$this->_item_description,$this->_total_count,$this->_unit_price,$this->_merchant_private_item_data);
    }
}


As i was using lot's of APP::import in many places to import vendor files in cakephp it consumes more memory.

Instead of using APP::import i used require_once() and the error did not occurs.


Use unset to destroy the reference to your object. When all references are gone the object will get destroyed.

You can also make use of the memory_get_usage function to see ow much memory you are using at the moment. Try using it to find out where your memory bottlenecks are.


Well if you done this for example:

for($i=0;$i<=10000;$i++)
{
    $Object = new MyObject();
    //Blah
    unset($Object);
}

your not only creating an object 10K times your also using unset 10K times which would decrease the speed of your application

your best of unsettling them over X amount if iterations like so:

$array = array();
$count = 0;
for($i=0;$i<=10000;$i++)
{
    $array[$i] = new MyObject();
    //Blah
    $i++;
    if($count == 500)
    {
        unset($array,$count);
        $array = $array();
        $count = 0;
    }
}

Now your memory should not reach peak, and your only using unset 20 times :)

This way your saving performances as well.


Without seeing the code, we can't tell exactly what is causing this error. It could be creating too many objects, but it could just as easily be creating too big an array or other data.

Either way regardless of what type of data you're creating that is throwing the error, it's likely to be a loop or recursive function running out of control that's the underlying cause, creating new data on every iteration, rather than you deliberately creating enough objects to overflow that much memory.

If you really do need to create enough data to fill that much memory then you can modify the maximum memory allowance in PHP.ini, but it's unlikely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜