Jump to content

OOP global variables


Manixat

Recommended Posts

Hello freaks,

 

I am having quite a difficult time working out how to use an instance of a certain class in all instances of all objects.

 

Example:

this is my main file ( index etc. ),

 

 

 

<?php

$a = new User();

$b = new HeaderBuilder($_SESSION['userid']);

?>
 

 

 

HeaderBuilder:

 

 

<?php
 
class HeaderBuilder{
 
    function __construct($id){
    echo $a->getUserById($id);
    }
 
}

 

Now my question is how do I use $a in HeaderBuilder's __construct without creating a new instance ?

Link to comment
https://forums.phpfreaks.com/topic/276090-oop-global-variables/
Share on other sites

This is logical but I just want it to be a single variable. Doing that to all my methods where I need user() is going to be a pain in the you know what. I tried with $_GLOBALS and it worked but it is just so long and annoying to type every time. Why can't I just simply assign a global variable in the main file O.o

When you pass a class to another class, you pass the reference to the original instance you don't create a new object.

$u = new User('ignace');

$a = new Foo($u);
$b = new Foo($u);
$c = new Foo($u);
$d = new Foo($u);

$u->setName('Manixat');
$c->printUserName(); // Manixat
$d->printUserName(); // Manixat
This is different from your normal procedural thinking. No matter how you turn it though if your class has a dependency on another class you'll still have to type it. Show us an example of what you mean by that you have to pass/create an instance in other classes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.