2016-01-20 61 views
0

我有父類和子類的PHP類。我不能在mysqli語句中使用父類中的變量作爲綁定變量(php將其視爲常量?)。請幫我看看 兩個PHP類:只有變量應該通過引用傳遞

<?php 
class cparent{ 
    public $var1; 
    public function __construct(){ 
     $this->var1 = 1; 
    } 
} 
class cchild extends cparent{ 
    private $mysqli; 
    public function __construct(){ 
     parent::__construct(); 
    } 
    public function getVar1(){ 
     return $this->var1; 
    } 
    public function some_mysqli_func(){ 
     if (!$stmt = $this->mysqli->prepare("INSERT INTO bla(var) VALUES (?)")){ 
       echo 'Error: ' . $this->mysqli->error; 
       return false; 
     } 
     $stmt->bind_param('i', $this->var1); 
     $stmt->execute(); 
    } 
} 
$child = new cchild(); 
echo $child->getVar1(); //ок 
$child->some_mysqli_func(); // Only variables should be passed by reference php 
?> 
+0

http://php.net/manual/en/language.oop5.visibility.php –

+0

'some_mysqli_func'是私人函數。你不能訪問它的類 –

+0

的外側當然,應該是公開的。這只是一個例子,請看看該函數的功能。 –

回答

2

這是罪魁禍首:

$stmt->bind_param('i', $this->var1); 

bind_param()方法使通過參考其轉讓,只能用一個變量來實現。 $this->var1在技術上屬於財產。您可以使用一個臨時變量:

$var1 = $this->var1; 
$stmt->bind_param('i', $var1); 

您可以只使用PDO避免了不少這樣的麻煩:

$statement->bindValue(':var', $this->var1); 

這將通過複製結合,而不是引用,並應你有更多的靈活性。

+2

應該完全可以傳遞*屬性*,參見https://3v4l.org/KS8pG。如果mysqli在這裏是個例外,我會感到驚訝。 – deceze

+0

有趣。我也發現,不像'PDO',沒有'bind_value()';所有的綁定都是參考。 – Will

+0

這兩種解決方案都可以,但如果現有的模塊具有數百個功能,我們有很強的重構,這是不可取的。也許有第三種方式與編輯子類參考相關聯?重寫var1,對於ex? –

相關問題