Accessing parent class objects & variables through $this? - php

I have one main class "main", which I use to store the configuration and a few objects. However, I am unable to access the objects & variables in a class which extends main, through $this.
Here is some of my main class:
<?php
class main{
// the configuration vars
public $config = array();
// the current user variables
public $uid; // contains the user ID
public $gid; // contains the group ID
// database variables
public $DB; // contains the connection
public $query_id; // contains the query ID
public $query_count; // how many queries have there been?
// cache variables
public $cache;
// start up functions
public function startup(){
// first, set up the caching
if(function_exists('memcache_connect') AND $this->config['use_memcache'] == true){
// start up memcache
require_once('memcache.class.php');
$this->cache = Cache::getInstance();
}
// now, set up the DB
$this->connectToDatabase();
// now, set up the user session
$this->setUserSession();
// are we logged in? If so, update our location
if($this->uid > 0){
// update location
$this->updateUserSession();
}
}
Here is an example of another class
<?php
class user extends main{
public function viewProfile($uid){
exit($this->config['session_prefix']); // displays nothing
if($this->cache->exists('key')){ // fails
The $config value is correctly set up, and I can read it within main but not any sub class.
The $cache->exists object just results in Call to a member function exists() on a non-object.
On index.php, the classes are loaded and set up. The Main class is setup first, and the startup function is called. The configuration array is passed before startup is called.
Can anyone suggest how I can fix this?

Are you sure your array is correctly set up.
This simple test works for me:
<?
class main {
public $test = "Woot";
}
class test extends main {
public function __construct() {
echo $this->test;
}
}
$t = new test();
Just for testing purposes, add a variable $test like in my example to the class main and try to echo it in the user constructor.
I would check if your cache is really set up correctly.
Probably the error is in this if statement:
if(function_exists('memcache_connect') AND $this->config['use_memcache'] == true){
One of these two conditions isn't met, so your $cache variable won't get initialized.

you can use parent:: to referance variables in the parent class.
parent::cache->exists('key')

You can access parent class's attributes by $this->attribute, so the problem should be that you are not calling the constructor of the parent...
Like this code is perfectly working:
<?php
class foo {
public $x="aa";
}
class bar extends foo {
public function barbar()
{
echo $this->x;
}
}
$b = new bar;
$b->barbar();
?>
Though you can also access parent class properties by Parent::attr()

Related

PHP Class Reference to Parent Variable

I'm building an API service and have a parent class:
classAPI {
public responseCode = "";
public responseMessageLog ="";
function run{
// here I call my user auth class
$oUser = new classUser(...);
}
}
Inside my classUser I do a bunch of stuff and then write a bunch of variables: responseMessageLog (which is running log of where the script went) and responseCode (which is set to 0 or 1 or whatever depending on success or failure or warning).
I need to access my responseCode and responseMessageLog variables from within my User class and my parent API class, but I don't really want to be passing these variables into each child class and then passing them back. I would like it that when I update the variable in the child class it updates everywhere in all my class.... kind of like a global variable would... but I know that's not a good idea.
How have others stopped passing variables down the rabbit trail of classes.
in this class I
Passing dependencies isn't a rabbit hole you want to avoid--it makes for more testable code. However, you don't need to pass every property, you can pass the parent object.
In your case just pass the classAPI object into the constructor of the classUser and in the constructor assign it to property. The classAPI properties are public so you can access them in an instance of classUser.
ClassAPI {
public $responseCode = "";
public $responseMessageLog ="";
public function run{
// here I call my user auth class
$oUser = new ClassUser($this, ...);
}
}
ClassUser {
public $myClassApi = null;
public function __construct(ClassAPI $myClassApi) {
$this->myClassApi = $myClassApi;
}
public function someFunction() {
echo $this->myClassApi->responseCode;
}
}
Added notes:
In case it comes up in another answer, don't use static properties to do what you're trying to do.
Capitalize your class names.
In production code I might add an initialization function in ClasUser instead passing the ClassAPI directly into the constructor.

can I access private variable in method in same class?

I have this controller
class PageController extends Controller
{
private $myid;
public funciton index(){
}
public function viewbyid($id){
$this->myid = $id;
return view('someview');
}
public function getRecord(){
$id = $this->myid;
echo $id; //it would be null here,if I am going to access this method.
return view('anotherview');
}
}
Yes, you can access private varible, in side class any where, Your using OOPS PHP. So may be problem is you might be accessing getRecord() method with diff object.
For Eg:
$obj=new PageController();
$obj->viewbyid("Test");
$obj->getRecord();//Then it will display the result
If your reinitialize an object or creating new object then that object will reallocate memory, so previous saved values will not be present.
For Eg:
$obj=new PageController();
$obj->viewbyid("Test");
$obj=new PageController();//$obj will allocate memory in diff location so your previous values will be initialized to default.
$obj->getRecord();//Then it will display result as null

PHP OOP - Pass data between classes through the calling class?

I'm struggling to find a correct approach to pass data between classes, which do not directly call each other, and are only related through a parent class (which I now use, but I consider it a dirty workaround rather than anything near a solution).
I have 3 classes both able to read input and write output, and based on configuration I set one to read, another one to write. It may even be the same class, they all share a parent class, but they are always two separate instances called from a controller class.
Currently I use this sort of functionality:
class daddy {
public static $data;
}
class son extends daddy {
public function setData() {
parent::$data = "candy";
}
}
class daughter extends daddy {
public function getData() {
echo parent::$data;
}
}
while($processALineFromConfig)
$son = new son;
$son->setData();
$daughter = new daughter;
$daughter->getData();
daddy::$data = null; //reset the data, in the actual code $daughter does that in parent::
}
Instantination of these classes runs in a loop, therefore I always need to reset the data after $daughter receives them, 'cos otherwise it would stay there for another pass through the loop.
I'm absolutely sure it's not how class inheritance is supposed to be used, however I'm struggling to find a real solution. It only makes sense the data should be stored in the controller which calls these classes, not the parent, but I already use return values in the setter and getter functions, and I am not passing a variable by reference to store it there to these functions 'cos I have optional parameters there and I'm trying to keep the code clean.
What would be the correct approach to pass data through the controller then?
Thanks!
The best option would be for two object share some other, third object. This would be the class for "third object" which will ensure the exchage:
class Messenger
{
private $data;
public function store($value)
{
$this->data = $value;
}
public function fetch()
{
return $this->data;
}
}
Then a class for both instance, that will need to share some state:
class FooBar
{
private $messenger;
private $name = 'Nobody';
public function __construct($messenger, $name)
{
$this->messenger = messenger;
$this->name = $name;
}
public function setSharedParam($value)
{
$this->messenger->store($value);
}
public function getSharedParameter()
{
return $this->name . ': ' . $this->messenger->fetch();
}
}
You utilize the classes like this:
$conduit = new Messenger;
$john = new FooBar($conduit, 'Crichton');
$dominar = new FooBar($conduit, 'Rygel');
$dominar->setSharedParameter('crackers');
echo $john->getSharedParameter();
// Crichton: crackers
Basically, they both are accessing the same object. This also can be further expanded by making both instance to observe the instance of Messenger.

OO PHP Accessing public variable from another class

I have a class like the following:
class game {
public $db;
public $check;
public $lang;
public function __construct() {
$this->check = new check();
$this->lang = DEFAULT_LANG;
if (isset($_GET['lang']) && !$this->check->isEmpty($_GET['lang']))
$this->lang = $_GET['lang'];
}
}
As you can see I have a public variable $lang that is also defined via the contructor.
The proble is that I want to access the result of this variable from other classes that are not directly related to this class, since I don't want to redeclare it for each different class.
So for example how can I call the result of that variable from another class, lets call it class Check ?
if you mark the public $lang; as static:
public static $lang;
you can access it via game::$lang;
if not static, you need to make an instance of game and directly access it:
$game = new game;
$game->lang;
static call inside of (current) class:
self::$lang;
late static bound call (to inherited static variable):
static::$lang;
call from child class to parent:
parent::$lang;
normal call inside of an instance (instance is when you use new Obj();):
$this->lang;
BTW:
variables defined by define('DEFAULT_LANG', 'en_EN'); are GLOBAL scope, mean, can access everywhere!
<?php
define('TEST', 'xxx');
class game {
public function __construct() {
echo TEST;
}
}
//prints 'xxx'
new game;
you can make it static variable, so you will be able to call it anytime anywhere, the diff is that instead of
$this->lang;
when editing it(Works inside class game only) you do :
self::$lang;
and when you call/edit it (Works everywhere) from anther class you do :
game::$lang
the idea of static class is that its exist only in one instance, so only one $lang exist in your program. but there is no need to load the whole class to get acsess to it.
How can I call the result of that variable from another class, lets call it class Check?
A variable doesn't have a result. If you mean to retrieve the state of that variable on a specific object $obj of class game then you can simply do:
$obj->lang
On a side note if $lang is publicly only read only you should protect it by defining it private or protected and create a getter method instead.
If you mean that you want to use the same variable name in another class I'd suggest you to consider inheritance:
class Check extends game { /* now Check has $lang */ }
but the variable of the two objects will be different.
Since the property is public, you can access it from outside the class as $objInstance->property. It doesn't matter if you're calling it from a function, procedural script, in another object. As long as you have the instance, you can call it's public property. Ex:
function foo($c) {
echo $c->lang;
}
foo($check);
Also, some advice on working with objects and such: It's considered better code if you don't create instances of objects in the other objects, but rather pass them in someway (either a setter method or through the constructor). This keeps the classes loosely coupled and results in code that is more reusable and easier to test. So:
class Game
{
...
public function __construct($check, $defaultLang, $get) {
$this->check = $check;
$this->lang = $defaultLang;
if (isset($get['lang']) && !$this->check->isEmpty($get['lang']))
$this->lang = $get['lang'];
}
...
$game = new Game(new Check(), DEFAULT_LANG, $_GET);
echo $game->check;
The first half of this article is an accessible explanation of what is known as Dependency Injection.

PHP: Can't access parent class variables

I am trying to access the variables from the parent class as shown below:
//PARENT CLASS
class InfoString{
private $username = "JOE";
public function _construct(){}
protected function get_username(){
return $this->username;
}
}
class Service extends InfoString{
//this class should now inherit the variables in InfoString, right??
public function _construct(){}
public function hello_username(){
echo "HELLO! ". parent::get_username();
}
}
and I call the class like so:
$a = new Service();
$a->hello_username(); //prints nothing, instead of the username
Instead of getting "HELLO! JOE", I get an empty string. What am I doing wrong here?
Also, suppose the class 'InfoString' will contain configuration parameters - is it a good idea to extend this class, or what would be the proper implementation to get the config variables from, say class 'InfoString' into another class???
Thanks.
You're just extending InfoString, so you can just use $this->get_username(); and it will work fine. :: is for calling static methods.
Also, you'd get an error if you'd increase your error level. Call error_reporting(E_ALL); this will give you clues to solve similar issues in the future.

Categories