我试图两次访问相同的方法,而不必两次创建对象。我制作了这段代码
<?php
class help{
public $cn;
public function __construct(){
require_once 'connection.php';
$this->cn = $c;// now $ cn brings the DB connection
}
public function executeQuery( $q ){
self::__construct(); /*I added it because according to I was trying to
invoke again the method without creating a
previous object, if I take it off, it marks me as
if there was no $ cn*/
header('Content-Type: application/json');
date_default_timezone_set('America/Mexico_City');
mysqli_set_charset($this->cn, "utf8");
return mysqli_query( $this->cn, $q );
}
}
$h = new help();
$q = "INSERT INTO FOOBAR (foo_id, bar_id) VALUES('foo','bar')";//new record
$r = $h->executeQuery( $q );//I will do something with $r
$q = "SELECT * FROM FOOBAR";//I retrive all records but the query fails
echo $h->executeQuery( json_encode( $q ) );;
?>
现在,该对象没有构造函数,如果它没有传递self :: __ construct();发送给我的是未宣布$ cn。
我该如何解决?我是否必须创建两个对象?
谢谢
修改 这是我的联系。
<?php
global $c;
$c = mysqli_connect("localhost","foo","bar","myDB");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
答案 0 :(得分:1)
您正在进行require_once()
来电,这是您的问题。你不会在第二次调用文件时重新包含该文件,但是由于你没有提取全局变量,所以第二次从第一次包含中返回的内容不可用。
如果可以多次包含该文件,您可以将require_once
设为普通require
,并按照您的预期设置变量。