如何将变量从类函数回显到另一个文件 [英] How to echo variable from the class function to the other file
问题描述
我只是OOP PHP的初学者.我想发生的是将变量从函数内的类回显到其他文件.请看一下这段代码:
class.library.php
文件中: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"];
}
}
}
和index.php
文件中:
include("class.library.php");
$data = new db_connect;
$data->settings();
我要发生的事情是简单地将名为$name
的变量从名为db_connect
的类的settings()
函数返回到index.php
文件.
我尝试过这样的事情:
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.
请告诉我这样做的正确方法.
PS:请原谅我用来解释我的问题的术语.我只是一个初学者.随时欢迎您纠正我.
您需要将$name
设置为类中的公共变量.
像这样:
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"];
}
}
}
然后,您应该能够在index.php
中像这样访问您的var:
$data = new db_connect;
$data->settings();
echo $data->name;
您可以阅读以了解有关var和函数可见性的更多信息 Php文档
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.
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
这篇关于如何将变量从类函数回显到另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!