2013-08-30 97 views
-1

我想从外部文件访问下面的方法(从公共类youth_teams)中的$ new_id变量,但我不知道如何。我已经从包含该方法的文件中正确地打印了lastInsertID,但也希望能够访问其他文件中的变量。从另一个文件访问存储在类中的变量

public function addTeam(
    $team_name, 
    &$error 
) { 
$query = $this->pdo->prepare('INSERT INTO `' . $this->table . '` (
    `team_name` 
) VALUES (
    :team_name 
)'); 
    $query->bindParam(':team_name', $team_name); 
    $query->execute(); 

    print_r($query->errorInfo()); 
    print $this->pdo->lastInsertID(); 
    $new_id = $this->pdo->lastInsertID(); 
    return $new_id;        
} 

下面是我从另一个文件试图代码:

sw::shared()->youth_teams->addTeam (
    $team_name, 
    $error 
); 

$temp_two = sw::shared()->youth_teams->addTeam->pdo->lastInsertID(); 
echo "new id: " . $temp_two . "<br>"; 

当然是不工作...什么是访问$ NEW_ID正确的路径?

回答

1

它应该是:

$temp_two = sw::shared()->youth_teams->addTeam($team, $error); 

addTeam()是返回$new_id的功能,所以你需要用()调用它。

如果你真的希望能够直接访问$new_id,你可以声明其全球:

public function addTeam(
    $team_name, 
    &$error 
) { 
    global $new_id; 
    ... 
+0

他也应该指定这个函数的参数 –

+0

有没有办法只取出$ new_id的值呢? – cpcdev

+0

我更新了我的原始代码以显示流程。在运行addTeam()方法后,我希望能够获取$ new_id值,然后使用它来运行另一种方法 – cpcdev

0

有什么错呢?

$sw = new sw(); 

$temp_two = $sw->addTeam($team, $error); 

echo "new id: " . $temp_two . "<br>"; 

如果你可以从外部文件中调用sw::shared(),您可以指定对象。

我也许我没有完全理解你的代码,如果没有,请充分说明如下:

sw::shared()->youth_teams->addTeam($team, $error); 

// 1. What does the shared() method do? 
// 2. What is the youth_teams property? 

如果它的需要,我可能会建议直接将分配到addTeam()功能,并使用上述格式仅返回标识。