r/PHPhelp • u/Ananas1312 • Feb 08 '25
PHP Classes via Core Class = no object
Hey guys, sorry for my bad english :(
I have 3 classes: 1 Core, 1 MySQL, 1 PageLoader.
The Core handles the other 2 classes.
in the constructor of the core ill open the db and set the object to a $. then i can return the db $var over the core..
class Core {
static private $DB;static private $pageLoad;
public function __construct(){self::setDB();self::setPageLoader();}private static function setDB(){self::$DB = new Database();}
public static function getDB(){return self::$DB;}
private static function setPageLoader(){self::$pageLoad = new PageLoader();}
public static function getPageLoader(){return self::$pageLoad;}}
ill use the mysql connection anywhere in script like:
Core::getDB()->NumRows($result);
this equeals like and works
$db = new DB();
$db->NumRows($result);
So Why is this not working for the pageload anywhere in script?
var_dump(Core::getPageLoader()); == NULL
Its the same procedure like my DB handling but its not working.. Why? :(
3
u/itemluminouswadison Feb 08 '25
Did you ever call the Core constructor? That's where the page loader is created and set right?
I don't think you need your constructor, it doesn't really make sense.
Just in the getters check for a static instance, if null, create and set it, and return it
4
u/equilni Feb 08 '25
I highly recommend to create the classes you need and pass them to the class(es) that need it (ie Dependency Injection).
This removed the need for your
Coreclass and no need for singletons.Unless you want a container
2
u/oxidmod Feb 08 '25
If you are using Core class as a facade via static methods then do not use constructor. Just make lazy getter to get your objects. I bet you've forgotten to create Core object in those cases where it isn't working. So constructor was never called and static properties weren't initialised
1
u/martinbean Feb 08 '25
Look into singletons.
Also settle on a method naming standard. You’re mixing PascalCase (i.e.
NumRows) with camelCase (i.e.setPageLoader). The convention in PHP projects tends to be camelCase.1
u/32gbsd Feb 08 '25
I dont even know what a core class is, lol.
1
u/Mastodont_XXX Feb 09 '25
Try to rethink your architecture and do not use "static" and "self".