2014-09-27 28 views
0

我努力學習OOP,我想從一個一個函數值傳遞給另一個類中,但由於某種原因,它給我的Notice: Trying to get property of non-object錯誤,任何想法?PHP傳球類值從一個功能到另一個

class test{ 
    function test($value){ 
    global $db; 
    $stmt = $db->prepare("SELECT * FROM some_table where some_column = ?"); 
    $stmt->bind_param('s', $value); 
    $stmt->execute(); 
    $res = $stmt->get_result(); 
    $fetch = $res->fetch_object(); 
    $this->test = $fetch->some_row;//this is the error line 
} 
     function do_something(){ 
     $name = $this->test; 
     return $name; 
     } 
     } 
$p = new test(); 
$p->test('test'); 
echo $p->do_something(); 
+1

它還指出你在那裏發生的確切行。由於您知道行號和變量,因此請使用'var_dump()'並檢查** actual **變量值。 – zerkms 2014-09-27 03:27:53

+0

@zerkms當我做var_dump時,它返回NULL。 – user2666310 2014-09-27 03:48:22

+0

所以 - 這就是爲什麼你會得到一個錯誤。你試圖調用一個NULL的方法,這是無稽之談。 – zerkms 2014-09-27 03:49:47

回答

0
class Test{ 

    public function test($value){ 
     global $db; 
     $stmt = $db->prepare("SELECT * FROM some_table where some_column = ?"); 
     $stmt->bind_param('s', $value); 
     $stmt->execute(); 
     $res = $stmt->get_result(); 
     $fetch = $res->fetch_object(); 
     $var_set = $fetch->some_row;//this is the error line 
     return $var; 
    } // end the funtion 

    function do_something($value){ 
     $name = $this->test($value); // you have to pass an value here 
     return $name; 
    } 
} 

$p = new Test; 
$return_value = $p->do_something($value); 
print_r($return_value); 
1

試試下面的代碼:

<?php 

    class test { 

     /** 
     * @var $test 
     **/ 
     public $test; 

     /** 
     * Constructor of current class 
     **/ 
     function __construct($value = "") { 

      /** 
      * Global variable $db must be defined before use at here 
      **/ 
      global $db; 

      $stmt = $db->prepare("SELECT * FROM some_table where some_column = ?"); 
      $stmt->bind_param('s', $value); 
      $stmt->execute(); 
      $res = $stmt->get_result(); 
      $fetch = $res->fetch_object(); 

      $this->test = $fetch->some_row; // Set return value to public member of class 
     } 

     /** 
     * Process and get return value 
     **/ 
     function do_something() { 

      $name = $this->test; 
      return $name; 
     } 
    } 


    $p = new test('test'); 
    // $p->test('test'); // You don't need to call this function, because this is the constructor of class 
    echo $p->do_something(); 
+0

依賴與類相同名稱的構造函數方法已被棄用 - 您確實應該將其稱爲[__construct](http://php.net/__construct)。 – TML 2014-09-27 05:23:06

相關問題