loading file on class construct - php

I'm working on a sql class, and trying to figure out how to retrieve data from an external php file, to be available in the entire class.
Im guesing i have to do something like this:
class sqlQuery {
protected $database = array();
function __construct(){
require_once (config.php);
}
}
class model extends sqlQuery {
function __construct() {
$this->connect($this->database['hostname'], $this->database['user'], $this->database['pass'], $this->database['database']);
}
}
The file might contain other information in the future, so I want it available to more then just the extended class.

Firstly you should call parent constructor in class model:
function __construct() {
parent::__construct();
// your other logic there
}
Then just change constructor of your parent class for filling $this->database array

Related

Set a variable of a class in another class

I have a class address_book in which I want to set $DBConnection using method from another class:
<?php
class address_book
{
protected $DBConnection;
public function __construct()
{
$this->DBConnection=new address_book_db();
$this->init();
}
public function init()
{
add_shortcode('address_book', array($this,'load'));
}
public function load()
{
var_dump($DBConnection);
}
}
Another class:
<?php
class address_book_db
{
protected $dbconnection;
public function __construct()
{
$this->dbconnection='1';
}
}
So var_dum should return '1' as it has to be assigned to protected $DBConnection; in the first class. I'm starting my learning of PHP OOP so probably everything is bad.
Any way it has to work like this.
In first class I load db name which is being loaded from another class using methods which determines db name (not developed yet because I just want to pass this constructed dbname to first class).
You're missing $this-> to refer to the class property.
The property's value contains another class, so you have to refer to that class its property as wel with a second ->
var_dump($this->DBConnection->dbconnection)

Parent and child classes not referencing correctly within a function PHP

I am building an MVC component and I'm getting stuck with an issue with a parent and child model. I have a few methods in the parent Model and they're not working with the database_class object
the constructor works fine
but when I use that object in the methods its like the constructor doesn't exist?
Class Controlller
{
public function __construct()
{
$this->childModel = $this->model('childModel');
} // end construct
// methods go here
}
Here are the models:
class childModel extends parentModel {
private $dbo;
public function __construct()
{
$dbobj = new Database_class;
$this->dbo = $dbobj;
}
//methods
}
class parentModel {
private $dbom;
public function __construct()
{
$dbombj = new Database_class;
$this->dbom = $dbombj;
var_dump($this->dbom); //working perfectly as database object
}
public function methodName()
{
var_dump($this->dbom); //not showing up as database object
}
}
I don't think this code is doing what you think it's doing. In childModel, you are overwriting the __construct method of the parentModel, so the __construct in the parentModel never gets called. Therefore $this->dbom should be null. Furthermore if you wish to use $this->dbom from the childModel, you should probably change the scope from private $dbom to protected $dbom. See this page for more info on that: http://php.net/manual/en/language.oop5.visibility.php

Php access a Global Class

this has been driving me nuts (Drinking Obscene amounts of Coffee and working all night doesn't help) I want to gain access to a class from wherever I am within the application. I instantiate the Class within my index page (which auto loads my lib/classes)But it seems I cannot gain global access to it. This is my index page:
function __autoload($class)
{
require LIBS . $class .'.php';
}
$Core = new Core($server, $user, $pass, $db);
This auto load my Lib/classes perfectly and then I instantiate my Core (This is auto loaded within my Lib/core.php)
Then within my Core is where I create the usual, a database connection, get and check the URL and where I instantiate a few classes (Which are auto loaded) I create a __construct and this is where I want to instantiate a Template class. I wish to have global access for accessing the class within any of my controllers and models.
class Core {
function __construct(DATABASE VARIABLES IN HERE)
{
$this->Template = new Template();
}
}
Ok so I thought I could access the Template Object by doing the following within my parent model and parent controller:
class Controller
{
public $Core;
function __construct()
{
global $Core;
$this->Core = &$Core;
}
}
The Controller is a parent extends all my controllers, therefore I assumed I could just write $this->Core->Template->get_data(); to access the a Template Method? This Seems to throw an error.
Im sure it must be something simple that I have overlooked, if anyone can give me a hand that would be great. This problem is driving me crazy.
Also a side note within my child controllers within my __construct I construct the Parent parent::_construct();
The Error seems to be Notice: Trying to get property of non-object and Fatal error: Call to a member function get_data() on a non-object.
class Controller
{
public $Core;
function __construct(Core $core)
{
$this->Core = $core;
}
}
class ControllerChild extends Controller {
function __construct(Core $core, $someOtherStuff){
parent::__construct($core) ;
//And your $this->Core will be inherited, because it has public access
}
}
note: You dont have to use & sign when working with objects. Objects are automatically passed by reference.
You could make Core a singleton and implement a static function to receive a pointer to the object.
define ('USER', 'username');
define ('PASS', 'password');
define ('DSN', 'dsn');
class Core {
private static $hInstance;
public static function getInstance() {
if (!(self::$hInstance instanceof Core)) {
self::$hInstance = new Core(USER, PASS, DSN);
}
return self::$hInstance;
}
public function __construct($user, $pass, $dsn) {
echo 'constructed';
}
}
Then within your Controller you can use:
$core = Core::getInstance();
Which should output constructed.
Edit
Updated to demonstrate how to construct via the static function w/ output.

Codeigniter constructor - Load database + set variables

I would like to know how I can add the following code to my codeigniter constructor:
$this->load->model('members_model');
$member = $this->session->userdata('email_address');
$viewdata['pagecontent'] = $this->members_model->get_profile($member);
The code is used throughout my controller and it seems silly to repeat it every time. When I try adding it to the constructor I am unable to reference the set variables.
This is the constructor so far:
public function __construct(){
parent::__construct();
Accesscontrol_helper::is_logged_in_super_user();
$this->load->model('members_model');
$member = $this->session->userdata('email_address');
$viewdata['pagecontent'] = $this->members_model->get_profile($member);
}
Why wouldn't the above code work? Do constructors require different code?
Constructor works, in this sense, like all other methods (and like functions), so your vars are subject to the variable scope.
Do:
class Mycontroller extends CI_Controller {
public $viewdata = array();
function __construct()
{
parent::__construct();
Accesscontrol_helper::is_logged_in_super_user();
$this->load->model('members_model');
// $this->load->library('session');
// $this->load->database();
// ^- if not already autoloaded
$member = $this->session->userdata('email_address');
$this->viewdata['pagecontent'] = $this->members_model->get_profile($member);
}
}
Then, in your other controller's methods, you just call the class property $this->viewdata, ex.
function index()
{
$this->load->view('myview',$this->viewdata);
}
And access it, in myview.php :
echo $pagecontent;
It looks like you are having some scope issues. Since the variables are declared inside of the __construct() method, that is the only method that is able to reference them. You would need to make them class variables in order to have access to them in all of your methods.
Try something like this:
class Your_class extends CI_Controller {
protected $member;
protected $viewdata;
public function __construct()
{
parent::__construct();
Accesscontrol_helper::is_logged_in_super_user();
$this->load->model('members_model');
$this->member = $this->session->userdata('email_address');
$this->viewdata['pagecontent'] = $this->members_model->get_profile($member);
}
}
Then you can reference $member and $viewdata in your other methods like this: $this->member
You may want to set this up a little differently, but hopefully you get the idea about variables and scope.

Problem regarding use of constructors in PHP

My problem is in using Codeigniter custom library but I think it is not specific to that and more related to use of constructors in PHP.
I am trying to create a custom controller library in Codeigniter like this...
class MY_Controller extends Controller {
var $data = array();
function MY_Controller() {
parent::Controller();
$this->data['err'] = 'no';
$this->load->helper('utilities');
}
}
Now I create a codeigniter controller class like this...
class api_controller extends MY_Controller {
function get_data() {
$this->data['view'] = "data";
$this->load->view("data_view", $this->data);
}
function get_xml() {
$this->data['part'] = "xml";
$this->load->view("data_view", $this->data);
}
}
I want to ask that if the controller class extending the MY_Controller is instantiated when I access urls like api_controller/get_data and api_controller/get_xml, does the constructor of parent class always get called upon, i.e., MY_Controller() is always called.
Am I correct in inferring the following
get_data() called
-> $data => array ('err' => 'no', 'view' => 'data')
get_xml() called
-> $data => array ('err' => 'no', 'part' => 'xml')
Your code looks like it's using the PHP4 syntax for constructors. You should switch to the PHP5 syntax.
PHP4:
class MyClassName {
function MyClassName() {...} //constructor.
}
PHP5:
class MyClassName {
function __construct() {...} //constructor.
}
You can then call the constructor of a parent class by calling parent::__constructor(); from within the child class's __constructor() method:
class MyClassName extends SomeOtherClass {
function __construct() {
//...code here runs before the parent constructor.
parent::__construct();
//...code here runs after the parent constructor.
}
}
For PHP in general the parent constructor is not called default if the child has a constructor.
Constructors. It can be called using parent::_construct();
If you're using php 5+ you should go with the new recommended style of using function __construct() instead of the old style with a function named the same as a class.
As for CI-specific stuff I can't help you, sorry!
If you do not override __construct() in MY_Controller then Controller's __construct() will get run.
If you override it and then called parent::__construct() then it will run your own and the parent's.
So if you wanted it to run the parent's and your own you would do this
class MY_Controller extends Controller
{
var $data = array();
function __construct()
{
parent::__construct();
// Your code here
}
}
Yes, the parent constructor it is always called (you may want to rewrite them as __construct() however, thinking also at codeigniter 2.0 ).
If you really are in doubt toss in it an echo and see it for yourself.
Also the $this->data part is correct to me
You are right in your affirmations about the data array contents. In you code you wrote:
function MY_Controller() {
parent::Controller();
so the parents's class constructor is being called. There are lots of comments about PHP4 and PHP5 syntax, but basically everithing is ok.
In your question you wrote
that if the controller class extending the MY_Controller is instantiated
that is not correct. The instance is an object of class api_controller, calling the MY_Controller constructor is made using the same object. That is not the same, that is basic for polimorphism.
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
}

Categories