我正在尝试学习oop并且我试图将一个值从一个函数传递到另一个函数但是由于某种原因它给了我一个错误Notice: Trying to get property of non-object
,任何想法?
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();
答案 0 :(得分: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();
答案 1 :(得分: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);