Extended class gets only initial value of parent's variable - php

class MyAppClass {
protected $_config = array();
protected $_template = '';
public function init( ){
require_once('core_config.php'); // Inside is $_SC_config with an array of values
$this->_config = $_SC_config;
$this->_template = new template;
echo $this->_template->echo_base();
}
}
class template extends MyAppClass{
public function echo_base() {
var_dump($this->_config); // returns empty array
}
}
$myApp = new MyAppClass;
$myApp->init();
What's wrong with code above so
var_dump($this->_config)
in template class returns empty array after init function?
Thanks in advance.

I think you don't get object programming yet. In MyAppClass::init method you create new object of template class which extends your MyAppClass class. I have no idea what do you want to acheve but I will show you snippet which works.
<?php
class MyAppClass {
protected $_config = array();
protected $_template = '';
protected function init( ){
//require_once('core_config.php'); // Inside is $_SC_config with an array of values
$this->_config = 'foo';
}
}
class template extends MyAppClass{
public function __construct(){
$this->init();
}
public function echo_base() {
var_dump($this->_config); // returns empty array
}
}
$myApp = new template;
$myApp->echo_base();

Related

How to send and extract class

I need to send and get Class into another class like a variable in MVC method :
class Demo {
private $vars = array();
function set($var , $data) {
$this->vars[$var] = $data;
}
function request() {
extract($this->vars);
var_dump($vars);
}
}
And i want to use above class into this :
class Test extends foo {
function __construct(){
$this->demo = new Demo();
}
function register(){
$user = Load::model('user');//Now User Is An Object
$this->demo->set('user',"$user");//This Is Error
$this->demo->request();
}
Catchable fatal error: Object of class user could not be converted to string in
remove the quotes
$this->demo->set('user', $user);
And don't forget to create your variable in your class scope
class Test extends foo {
public $demo;
should do the trick
class Test extends foo {
protected $demo; // you missed to declare this variable
function __construct(){
$this->demo = new Demo();
}
function register() {
$user = Load::model('user');//Now User Is An Object
$this->demo->set('user', $user);
$this->demo->request();
}
}

how to use objects created within the parent class in the child class PHP

I have this code and i´m trying to use a object
<?php
class Controller {
public $_view;
public function __construct() {
$this->_view = new View();
return $this->_view;
}
}
class View {
public $_params = array ();
public function set_params($index_name,$valores) {
$this->_params[$index_name] = $valores;
}
public function get_param($index_name){
return $this->_params[$index_name];
}
}
?>
i would like to do this:
class Index extends Controller {
public function index() {
$model = Model::get_estancia();
$usuarios = $model->query("SELECT * FROM usuarios");
$this->_view->set_params(); // cant be used.
$this->load_view("index/index");
}
}
i would like to use the set_parms function.
but i can't see the View Function, then i can not use.
Can someone explain and advise me a good and safe way?
Correction from Phil: If a __construct() method isn't found, PHP will revert to legacy constructor syntax and check for a method with the same name as the object. In your case the method index() is being treated as the constructor, and is preventing the parent's constructor from loading the view object into the $_view property.
You can force a class to inherit a parent's constructor by defining __construct() in the child and calling the parent's constructor:
public function __construct() {
parent::_construct();
}
Here is the fixed code:
<?php
class Controller {
public $_view;
public function __construct() {
$this->_view = new View();
return $this->_view;
}
}
.
class View {
public $_params = array ();
public function set_params($index_name,$valores) {
$this->_params[$index_name] = $valores;
}
public function get_param($index_name){
return $this->_params[$index_name];
}
}
.
class Index extends Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$model = Model::get_estancia();
$usuarios = $model->query("SELECT * FROM usuarios");
$this->_view->set_params(); // cant be used.
$this->load_view("index/index");
}
}

Inheritance in PHP - Creating child instance and calling parent method

I have something like this:
class MyParent {
protected static $object;
protected static $db_fields;
public function delete() {
// delete stuff
}
public static function find_by_id($id = 0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM " . static::$table_name . " WHERE id=" . $database -> escape_value($id) . " LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql = "") {
global $database;
// Do Query
$result_set = $database -> query($sql);
// Get Results
$object_array = array();
while ($row = $database -> fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record) {
$object = self::$object;
foreach ($record as $attribute => $value) {
if (self::has_attribute($attribute)) {
$object -> $attribute = $value;
}
}
return $object;
}
}
class TheChild extends MyParent {
protected static $db_fields = array('id', 'name');
protected static $table_name = "my_table";
function __construct() {
self::$object = new TheChild;
}
}
$child= TheChild::find_by_id($_GET['id']);
$child->delete();
I get this: Call to undefined method stdClass::delete() referring to the last line above. What step am I missing for proper inheritance?
You never actually instanciate the TheChild class, which should be done by
$var = new TheChild();
except in TheChild constructor itself.
So, the static $object field is never affected (at least in your example), so affecting a field to it (the line $object -> $attribute = $value; ) causes the creation of an stdClass object, as demonstrated in this interactive PHP shell session:
php > class Z { public static $object; }
php > Z::$object->toto = 5;
PHP Warning: Creating default object from empty value in php shell code on line 1
php > var_dump(Z::$object);
object(stdClass)#1 (1) {
["toto"]=>
int(5)
}
This object does not have a delete method.
And as said before, actually creating a TheChild instance will result in an infinite recursion.
What you want to do is this, probably:
class TheChild extends MyParent {
protected static $db_fields = array('id', 'name');
protected static $table_name = "my_table";
function __construct() {
self::$object = $this;
}
}
Edit: Your updated code shows a COMPLETE different Example:
class MyParent {
protected static $object;
public function delete() {
// delete stuff
}
}
class TheChild extends MyParent {
function __construct() {
self::$object = new TheChild;
}
}
$child = new TheChild;
$child->delete();
Calling "Child's" Constructor from within "Child's" Constructor will result in an infinite loop:
function __construct() {
self::$object = new TheChild; // will trigger __construct on the child, which in turn will create a new child, and so on.
}
Maybe - i dont know what you try to achieve - you are looking for:
function __construct() {
self::$object = new MyParent;
}
ALSO note, that the :: Notation is not just a different Version for -> - it is completely different. One is a Static access, the other is a access on an actual object instance!

What's wrong in this singleton class

I've 3 classes. [1]Singleton [2]Load [3]Dashboard . In Load class there is one method called 'model()'. Where i'm initializing data for singleton object by using this code.
$obj = Singleton::getInstance();
$obj->insertData('email', 'mail#domain.com');
Again, from Dashboard class there is one method called 'show()' from where i'm trying to print the Singleton object data. But, here i can see all the data of Singleton object except the data which has been initialized by 'model' method of 'Load' class.
Here is my full code...
<?php
//---Singletone Class---
class Singleton
{
// A static property to hold the single instance of the class
private static $instance;
// The constructor is private so that outside code cannot instantiate
public function __construct() {
if(isset(self::$instance))
foreach(self::$instance as $key => &$val)
{
$this->{$key} = &$val;
}
}
// All code that needs to get and instance of the class should call
// this function like so: $db = Database::getInstance();
public static function getInstance()
{
// If there is no instance, create one
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Block the clone method
private function __clone() {}
// Function for inserting data to object
public function insertData($param, $element)
{
$this->{$param} = $element;
}
}
//---LOAD class---
class Load
{
function __construct()
{
$obj = Singleton::getInstance();
$obj->insertData('country', 'INDIA');
}
function model()
{
$this->name = 'Suresh';
$obj = Singleton::getInstance();
$obj->insertData('email', 'mail#domain.com');
}
function msg()
{
return('<br><br>This message is from LOAD class');
}
}
$obj = Singleton::getInstance();
$load = new load();
$obj->load = $load;
//---Dashboard Class---
class Dashboard extends Singleton
{
function __construct()
{
parent::__construct();
}
function show()
{
echo "Default data in current Object";
echo "<br>";
print_r($this);
echo $this->load->msg();
$this->load->model();
echo "<br><br>Data in current Object after post intialization";
echo "<br>";
print_r($this);
}
}
$dashboard = new dashboard();
$dashboard->show();
If your singleton was truly a singleton then the update would have worked. I'm suspecting that you may have multiple instances of the singleton class that is initialized.
Edit:
Also its not a good idea to inherit from a true singleton class.
You need to remove the inheritance that Dashboard has on Singleton
Edit:
Best practice on PHP singleton classes
I don't like your direct access to an object like an array. This one is a better approach [see here]:
You should call it like this:
$obj = Singleton::getInstance();
$load = new Load();
$obj->insertData( 'load', $load );
Implementation of Singleton:
class Singleton
{
// A static property to hold the single instance of the class
private static $instance;
// my local data
protected $_properties;
// You might want to move setter/getter to the end of the class file
public function __set( $name, $value )
{
$this->_properties[ $name ] = $value;
}
public function __get( $name )
{
if ( ! isset( $this->_properties[ $name ] )) {
return null;
}
return $this->_properties[ $name ];
}
// No need to check, if single instance exists!
// __construct can only be called, if an instance of Singleton actually exists
private function __construct() {
$this->_properties = array();
foreach(self::$instance as $key => &$val)
{
$this->_properties{$key} = &$val;
}
}
public static function getInstance()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Function for inserting data to object
public function insertData($param, $element)
{
$this->_properties{$param} = $element;
}
// Block the clone method
private function __clone() {}
}

How to pass php variable into a class function?

I want to pass php variable $aa into a class function. I have read some articles
in php.net, but I still don't understand well. Can anyone help me put the variable into this class? thanks.
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct() {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
Simply put the variable names in the constructor.
Take a look at the snippet below:
public function __construct( $aa )
{
// some content here
}
I'm not sure what you mean... do you mean you want to access $aa in a function? If so:
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct() {
global $aa;
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
Or, on a per instance basis, you can do things like:
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct($aa) {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
new Action($aa);
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct($aa) {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
And use it like this:
$instance = new Action('something');
I don't know php, but my logic and google say this:
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct($aa) {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
$object = new Action('some word');
This is simply called pass a variable as parameter of a function, in this case the function is the constructor of Action

Categories