I have a main class which initializes another class in a function of main class and I need to get a variable (in this case $this->db) from the main class to that another class. For example, I have a main class Wordle_Admin:
class Wordle_Admin
{
public function __construct()
{
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
}
public function views()
{
include 'Wordle_Admin_Views.php';
$wsa = new Wordle_Admin_Views();
$view = @$_GET['view'];
$id = @$_GET['id'];
$type = @$_GET['type'];
$action = @$_GET['action'];
$msg = @$_GET['msg'];
if( !empty( $view ) && method_exists( $wsa, $view ) ):
$wsa::$view($id, $type, $action, $msg);
elseif( !empty( $view ) && !method_exists( $wsa, $view ) ):
echo'View does not exist.';
else:
$wsa::index($id, $type, $action, $msg);
endif;
}
}
And I have another class:
class Wordle_Admin_Views extends Wordle_Admin
{
public function __construct()
{
parent::__construct();
}
public function index( $id = "", $type = "", $action = "", $msg = "" )
{
$this->db->query('SELECT * FROM wordle_post');
}
}
I can not use $this->db in Wordle_Admin_Views, it returns:
Fatal error: Using $this when not in object context in C:\Server\wordle\w-includes\Wordle_Admin_Views.php on line 22
So my question is, how can I pass a variable from parent class to class? All kind of help is appreciated, pointers on what to do differently are also accepted with open hands.
Using $this when not in object contexthas nothing to do with parents or children. It means you're using$thisin a function that's called statically, or outside an object. How are you calling these functions?