I’m trying to load libraries dynamically with a loop then add them to $this and I’m trying to use instanceof to see if it’s already been initiated before trying to initiate it again:
$libraries = array('strings');
foreach ($libraries as $lib) {
require_once('lib/'.$lib.'.lib.php');
if(!($this->lib_{$lib} instanceof $lib)){
$this->lib_{$lib} = new $lib();
} else {
continue;
}
}
But when I try this I just get an 500 internal server error from apache.
The error I get is:
[15-Feb-2012 10:31:21] PHP Notice: Undefined property: load::$lib_ in /home/wwwsrv/public_html/system/core.lib.php on line 57
(line 57 refers to the line with the if statement)
Any ideas?
Looks like you don’t have a member variable initialized which matches YOUR_CLASS::$lib_SOMELIB, so PHP is throwing a notice.
I would try something like:
Also, you may want to look into using magic methods; __set and __get to dynamically set member variables of YOUR_CLASS, so you don’t need to maintain a laundry list.
— Edit #2 —
Not sure why you are getting the stdObject error, might be that already tried initializing the value earlier. Take a look at this snippet, and see if it helps. I tested it and works.
— Edit #1 —
After closer inspection of your code, it appears you are trying to create an autoloader coupled with a lazy-load pattern. Lazy-loading works well in some situations, but keep in mind that it will be difficult for calling code to set specific member attributes of the objects being instantiated, if this is a non-issue, then disregard.
Also, I would recommend reading up on PHP’s built-in spl_autoload capabilities.