[英]php oops including another page
Here is my code in database.php 这是我在database.php中的代码
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "ss";
$con = new PDO('mysql:host=localhost;dbname=app', $db_username, $db_pass);
In my class page 在我的课程页面
include_once "database.php";
class article_fun
{
public function myfun()
{
$sqlcreate = $con->query("selct query")
}
}
How do we do we use $con->query("select query")
getting an error Undefined variable: con
how to fix this? 我们如何使用$con->query("select query")
获取错误Undefined variable: con
如何解决此问题?
Pass $con
as a parameter to article_fun::myFun()
将$con
作为参数传递给article_fun::myFun()
class article_fun
{
public function myfun($con)
{
$sqlcreate = $con->query("selct query")
}
}
FYI, in PHP it is convention to start class names with a capital letter and use camelCase: 仅供参考,在PHP中,习惯上以大写字母开头的类名并使用camelCase:
class ArticleFun
Your created variables are outside of the function scope. 您创建的变量不在函数范围内。
So you can't access variables outside a function from inside the function. 因此,您不能从函数内部访问函数外部的变量。
Try to use the magic function __construct()
尝试使用魔术函数__construct()
Like this: 像这样:
class article_fun{
private $_con;
public function __construct( $con ){
$this -> _con = $con;
};
public function myfun(){
$sqlcreate = $this -> _con->query("selct query")
}
}
Now you just have to pass the $con
var to the Class like so: 现在,您只需要像这样将$con
var传递给Class:
$article_fun = new article_fun( $con );
use this 用这个
class article_fun
{
private $con;
public function __construct($con){
$this->con=$con;
}
public function myfun()
{
$sqlcreate = $this->con->query("selct query")
}
}
call this 叫这个
include_once "database.php";
new article_fun($con);
or use this 或使用这个
class article_fun
{
private $con;
public function __construct(){
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "ss";
$this->con = new PDO('mysql:host=localhost;dbname=app', $db_username, $db_pass);
}
public function myfun()
{
$sqlcreate = $this->con->query("selct query")
}
}
class article_fun
{
public function myfun()
{
global $con;
$sqlcreate = $con->query("select query")
}
}
Your variable is definied in the global context and you try to use it in a method of a class. 您的变量是在全局上下文中定义的,您尝试在类的方法中使用它。
Use global variable 使用全局变量
$GLOBALS['con'] = $yourConnection;
Check this link for answer How to declare a global variable in php? 检查此链接以获取答案如何在php中声明全局变量?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.