i having problem understanding what is wrong with my inheritance. I just can not call most of the function of the parent. below is the function i am stuck.
class MySQLi_DB extends mysqli {
private static $_instance = null;
private function __construct($db="test",$host="localhost", $user="root", $pass="")
{
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
static public function getDB()
{
if(self::$_instance == null)
{
self::$_instance = new MySQLi_DB();
}
return self::$_instance;
}
public function insert($table,$data)
{
$sql = $this->getQuery($table,$data);
print $sql;
}
public function getQuery($table, $inserts)
{
$lambda = function($value){
return $this->real_escape_string($value);
};
$values = array_map($lambda,$inserts);
$keys = array_keys($inserts);
return 'INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')';
}
I am having problem calling real_escape_string() function . i have tried using $this->real_escape_string() but i just have to see this error
Fatal error: Using $this when not in
object context in
D:\wamp\www\Driver\MySQLi_DB.php on
line 49
ok may be that could be limitation of lambda function but i have tried it other way by declaring a callback for array_map that also doesn’t allow me to call real_escape_string.
i am calling the function as below.
require_once 'MySQLi_DB.php';
$db = MySQLi_DB::getDB();
$insert_data = array("cmsId"=>444,"pageName"=>"New Insert");
$db->insert("cms",$insert_data);
Please point out where i am doing wrong and what could be the best way to do it. thanks
You can’t use the $this keyword into a lamba function as the scope of the function does not extend to the object whose method contains the lambda
Try a different approach:
Addendum
If real_escape_string is not a method of your object but the standard msqli method you should change the line
to
to call the method real_escape string.
The array
array(self::$_instance, 'real_escape_string')is a callback array and it is used when you want to call an object method.The php manual states
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1
and self::$_instance is the mysqli instance you want to call