有一种方法可以将$id保存在类中,以便下次运行函数时可以使用它?
到目前为止,我在执行查询后在函数内部获得了正确的$id,但是当我重新运行函数时,我再次得到一个未初始化的$id。
class ShortURL {
public $id;
public $val2;
function insert() {
$conn = new PDO( DB_DSN, DB_USER, DB_PASS );
$sql = "INSERT INTO art ( val1, val2 ) VALUES ( :val1, :val2 )";
$st = $conn->prepare( $sql );
$st->bindValue( ":val1", self::hash ( $this->id+1 ), PDO::PARAM_STR );
$st->bindValue( ":val2", $this->val2, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
}
如果在执行函数之前创建类的新实例,则变量将被重置。因此,当您执行以下操作时:
$insert = new ShortURL();
$insert->insert();
echo $insert->id;
//You should see your value correctly
$insert = new ShortURL();
echo $insert->id;
//Now that you initialized the function again, the value is cleared
尝试创建类,然后重用该类的同一实例。