在foreach循环内重新实例化对象

时间:2014-10-09 06:32:01

标签: php

我正在研究某人的代码。代码中有一个函数。

就像是:

function send_notification($device_token)
{
    $apn = new APN();
    $apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
    $apn->connectToPush();
    ............................
    ............................
}

然后在foreach循环中,他调用函数。

foreach($alluser as $user)
{
    send_notification($user['device_token']);
}

现在,如果我运行上面的代码,那么它会显示APN Failed to connect: Something wrong with context

所以我在代码中改变了一些东西。

$apn = new APN();
foreach($alluser as $user)
{
    $apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
    $apn->connectToPush();
    ............................
    ............................
}

我在foreach循环之外创建了类的对象然后它正在工作 但最糟糕的是,我必须在每个地方写上面的代码(这个页面包含其他foreach)。

那么我怎样才能以聪明的方式解决上述问题呢?

FULL CODE (Just some part)

<?php
foreach($alluser as $user)
{
    send_notification($user['device_token']);
}

function send_notification($device_token)
{
    $apn = new APN();
    $apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
    $apn->connectToPush();
    ............................
    ............................
}
?>

旁注:我想知道的是,每当我创建新的类实例时,为什么它不起作用?

2 个答案:

答案 0 :(得分:1)

您可以使用全局对象,然后您不需要反复创建对象,例如

<?php
$apn = new APN();
foreach($alluser as $user)
{
    send_notification($user['device_token']);
}

function send_notification($device_token)
{
    global $apn;
    $apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
    $apn->connectToPush();
    ............................
    ............................
}
?>

答案 1 :(得分:1)

您可以将APN实例作为函数的必需参数,并且只在循环之前实例化。

<?php
$apn = new APN();
foreach($alluser as $user)
{
    send_notification($user['device_token'], $apn);
}

function send_notification($device_token, APN $apn)
{
    $apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
    $apn->connectToPush();
    ............................
    ............................
}

另一种方法是使用单身人士:

class APN {
    private static $instance = null;
    public static function getInstance() {
        if (null === self::$instance) {
             self::$instance = new self;
         }
         return self::$instance;
    }
    //.... whatever your class does
}

foreach($alluser as $user)
{
    send_notification($user['device_token'], $apn);
}

function send_notification($device_token)
{
    $apn = APN::getInstance();
    $apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
    $apn->connectToPush();
    ............................
    ............................
}

注意Singleton pattern也有它的缺点,如紧耦合,这使得测试更加困难并且还隐藏了依赖性:

Singleton Antipattern

所以我的建议是第一种方法。