Jump to content

OOP global variables


Go to solution Solved by Hall of Famer,

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 ?

Edited by Manixat
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

Edited by Manixat
  • Solution

Well good OOP design requires no global variable or at least minimum usage of globals. Technically you can achieve the same functionality as global variables with Singleton/Registry pattern, but these are often considered anti-patterns.

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. Edited by ignace
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.