问题
I am just a beginner at OOP PHP. What I want to happen is to echo the variable from the class inside the function to other file. Please take a look at this code:
in class.library.php
file:
class db_connect {
// Other functions and variables here
function settings() {
$sql="SELECT * FROM lms_admin_settings";
$result = $this->conn->query($sql);
while($data = $result->fetch_assoc()) {
$name = $data["name"];
}
}
}
and in index.php
file:
include("class.library.php");
$data = new db_connect;
$data->settings();
what I want to happen is to simply echo the variable named $name
from settings()
function of class named db_connect
to index.php
file.
I tried something like this:
include("class.library.php");
$data = new db_connect;
$data->settings();
echo $name; // I tried this but didn't work, I put this just to make things more clearly.
Please tell me the correct way of doing that.
PS: Pardon for what terms that I've used to explain my problem. I am just a beginner. You are always welcome to correct me.
回答1:
You need to set $name
as a public var into your class.
Like this:
class db_connect {
// We declare a public var
public $name = "";
function settings() {
$sql="SELECT * FROM lms_admin_settings";
$result = $this->conn->query($sql);
while($data = $result->fetch_assoc()) {
$this->name = $data["name"];
}
}
}
Then you should be able to access your var like this in index.php
:
$data = new db_connect;
$data->settings();
echo $data->name;
You can read this to learn more about vars and function visibility Php doc
回答2:
The problem is, you're not returning anything from the settings()
method. Return the entire result set from the settings()
method and loop through it, like this:
class.library.php
class db_connect {
// Other functions and variables here
function settings() {
$sql="SELECT * FROM lms_admin_settings";
$result = $this->conn->query($sql);
return $result;
}
}
index.php
include("class.library.php");
$data = new db_connect;
// catch the result set
$result = $data->settings();
// loop through the result set
while($data = $result->fetch_assoc()) {
// display
echo $data['name'] . "<br />";
}
回答3:
<?php
class db_connect {
// Other functions and variables here
public $name;
function settings() {
$sql="SELECT * FROM lms_admin_settings";
$result = $this->conn->query($sql);
while($data = $result->fetch_assoc()) {
$this->name = $data["name"];
}
}
}
//index.php
include("class.library.php");
$data = new db_connect;
$data->settings();
echo($data->name);
?>
来源:https://stackoverflow.com/questions/35091778/how-to-echo-variable-from-the-class-function-to-the-other-file