I am making a framework in PHP. I have an import function in library/core.php.
I can use the function like this:
$core->import("someclass");
This is the function:
public function import()
{
$import_resources = func_get_args();
$check_directories = array("library", "template", "view", "action", "errors");
$instances = array();
foreach($import_resources as $resource)
{
for($i = 0; $i <= count($check_directories) - 1; $i++)
{
if(file_exists($this->appRoot() . $check_directories[$i] . "/" . $resource . ".php"))
{
$classes = get_declared_classes();
include ($check_directories[$i] . "/" . $resource . ".php");
$included_classes = array_diff(get_declared_classes(), $classes);
$last_class = end($included_classes);
$last_class_lowercase = strtolower($last_class);
$this->$last_class_lowercase = new $last_class();
// create an instance of the included class and attach it to the Core Class
}
else
{
}
}
}
}
So in an other class, I can use it like this:
$core->import("view");
$core->view->get();
The whole point of this, was to make the included class available in another class, when it is extended.
class Someclass extends Core
{
public function somefunc()
{
$this->view->get(); // This does not work.
}
}
How could I make it work like this? This is a very important part of the framework, because this is how it works. I think it works similar in popular frameworks like CodeIgniter too.
I was trying to use parent::view->get(), but I guess I don't fully understand it.
I hope I can figure this out, because it is holding me down in my work. Thank you in advance.
What you want to do is use "Magic Methods", this particular one (__get() this gets properties not accessible from outside). You will want to use it like this:
<?php
// --- Begin Importer.php --------------------
class Importer{
protected $classes = array();
public function __get($method_name){
if(array_key_exists($method_name, $this->classes)){
return $this->classes[$method_name];
}
}
public function import($class_name){
// Do this or use an auto loader
require_once __DIR__ . "/../classes/$class_name";
$this->classes[$class_name] = new $class_name();
}
}
// --- End Importer.php ---------------------
// --- Begin MyClass.php --------------------
class MyClass{
public function get(){
return "hello";
}
}
// --- End MyClass.php ----------------------
// --- Where ever you call Importer ---------
$importer = new Importer();
$importer->import("MyClass");
echo $importer->MyClass->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With