2014-09-27 2 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()'를 취하고 ** 실제 ** 변수 값을 확인하십시오. – zerkms

+0

@zerkms var_dump 할 때 NULL을 반환합니다. – user2666310

+0

그래서 오류가 발생합니다. 당신은 말도 안되는'NULL' 메쏘드를 호출하려고합니다. – zerkms

답변

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

관련 문제