gpt4 book ai didi

php - 如何在php中的另一个类中使用分配给另一个类的属性的类的实例

转载 作者:搜寻专家 更新时间:2023-10-31 21:38:14 25 4
gpt4 key购买 nike

我正在用 PHP 制作一个框架。我在 library/core.php 中有一个导入函数。

我可以像这样使用这个函数:

$core->import("someclass");

这是函数:

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
{

}
}
}

}

所以在另一个类中,我可以这样使用它:

$core->import("view");
$core->view->get();

这样做的全部目的是使包含的类在扩展时在另一个类中可用。

class Someclass extends Core
{
public function somefunc()
{
$this->view->get(); // This does not work.
}
}

我怎样才能让它像这样工作?这是框架的一个非常重要的部分,因为它就是这样工作的。我认为它在 CodeIgniter 等流行框架中的工作方式也类似。

我试图使用 parent::view->get(),但我想我没有完全理解它。

我希望我能解决这个问题,因为它阻碍了我的工作。提前谢谢你。

最佳答案

您想要做的是使用“魔术方法”,这个特殊的方法(__get() 这会获取无法从外部访问的属性)。你会想像这样使用它:

<?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();

关于php - 如何在php中的另一个类中使用分配给另一个类的属性的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14074412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com