【问题标题】:Returning A Variable From Outside Class从外部类返回一个变量
【发布时间】:2013-05-06 07:58:47
【问题描述】:

我知道这可能是我迄今为止问过的最愚蠢的问题......但我一直在寻找参考点,而且有很多随机问题,最难找到。 我知道它最有可能是正确语法的问题,但对于我的一生,经过多次试验和错误,我知道它可能更容易问......(另外,lastInsertId() 不会是一个可能的解决方案因为还有其他省略的代码)......它必须是一个全局变量才能正确返回......据我所知......不是明确的

问题:我怎样才能正确地回显这个变量:

回显代码

$customer = new SoClassy();
$var1 = "test 1";
$var2= "test 2";
$var3= "test 3";
try {
$customer->add_function($var1,$var2,$var3);
$last_insert_id= $customer->$return_this_variable; 

echo "HERE:  ";
echo $last_insert_id;
}
catch (Exception $e) {
print "Error: " . $e->getMessage();
}

类代码(不同的*.php)

 function add_function($var1,$var2,$var3)
     {
        $data = array(
            'position_one' => $var1,
            'position_two' => $var2,
            'position_three' => $var3
        );
        try {
            $this->db->insert($this->config->database->tables->table_name, $data);
            $return_this_variable = $this->db->lastInsertId();
       return $return_this_variable;
            }
        catch ...{}
        catch ...{}
    }

【问题讨论】:

  • 我不确定我是否理解您的问题。你需要退货什么?在任何情况下,无论从方法/函数返回的内容还是从外部范围(即全局)中已经可见的内容,您都可以使您的函数可用。前者总是更明智的选择,因为它减少了依赖性。

标签: php zend-framework variables return


【解决方案1】:

如果我正确理解了这个问题.. 该函数将返回您想要的值。所以你将函数调用分配给你的变量:

$last_insert_id = $customer->add_function($var1,$var2,$var3);

【讨论】:

  • 但不幸的是,我不能专门使用它由于省略了代码,它会在该摘录下方运行多个插入
  • 好吧,您的函数进行查询并获取lastInsertID() 并将其放入$return_this_variable,然后返回该值.. 所以假设您的查询内容是正确的,那就是您得到的$last_insert_id
  • 函数本身完美运行....
  • 我需要的最后一点信息...如果我使用它来实际设置变量,那么它实际上会运行该函数两次,所以我可以摆脱它上面的 $customer->function... 行,对吗?
  • 所以你只需执行我发布的单行而不是$customer->add_function($var1,$var2,$var3); $last_insert_id= $customer->$return_this_variable;
【解决方案2】:

考虑采用一种替代方法来替代向您建议的方法,以防您需要传递其他东西而不仅仅是一个函数结果。

class SoClassy {

protected $itemId;

public function add_function($var1,$var2,$var3)
     {
        $data = array(
            'position_one' => $var1,
            'position_two' => $var2,
            'position_three' => $var3
        );
        try {
            $this->db->insert($this->config->database->tables->table_name, $data);
            $this->itemId = $this->db->lastInsertId();
            }
        catch ...{}
        catch ...{}
    }

}


public function doSomethingElse() {  ... }

public function doItAll($var1,$var2,$var3) {
    $this->add_function($var1,$var2,$var3)
    $this->doSomethingElse();
    return $this->itemId;
}

}

如果您需要在您的方法中执行大量操作,您可能需要使用类似的方法,以避免它成为一个怪物。

您可以在 doSomethingElse 和所有其他类方法中对 itemId(或其他类变量)做任何您想做的事情。基本上,您将需要的所有临时变量保存在一个地方,而不会使它们成为全局变量,从而冒着名称冲突的风险。

【讨论】:

  • 它是一个非常疯狂的程序,我现在只是在扩展功能,所以采取了这一点,但我不会完全重新设计轮子......如果你赶上我的漂移。建议 +1!
  • 很高兴这对您有用。如果你对 db 很感兴趣,我建议你看看 Doctrine ORM 之类的东西。为您处理大部分关系面向对象的转换麻烦。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
相关资源
最近更新 更多