2012-12-28 4 views
3

PHP로 프레임 워크를 만들고 있습니다. library/core.php에 가져 오기 기능이 있습니다.다른 클래스의 다른 클래스의 속성에 할당 된 클래스의 인스턴스를 PHP에서 사용하는 방법

나는이 같은 기능을 사용할 수는 :

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

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("someclass"); 

이 기능입니다

이 모든 내용은 확장 될 때 포함 된 클래스를 다른 클래스에서 사용할 수 있도록하는 것이 었습니다.

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

어떻게하면 좋을까요? 이것은 프레임 워크에서 매우 중요한 부분입니다. 이것이 작동하는 방식이기 때문입니다. CodeIgniter와 같은 인기있는 프레임 워크에서도 이와 유사하게 작동한다고 생각합니다.

parent::view->get()을 사용하려고했지만 완전히 이해하지 못했습니다.

내 작업에서 나를 붙잡고 있기 때문에 이것을 알아낼 수 있기를 바랍니다. 미리 감사드립니다.

+0

"핵심"이란 무엇입니까? 수입인가? 그렇다면 '수입'이라고 불러야 할 것입니다. –

+0

왜 자동 로딩을 사용하지 않는가? 더 좋은 방법은 PSR-0을 따르고 표준 오토로더를 사용하는 것입니다. –

+0

@Waleed Khan; 아니요, 아니요, 핵심 기능은 모든 핵심 기능입니다. 그것은 내 프레임 워크에있는 모든 PHP 파일에 포함되어야합니다. 핵심 가져 오기 기능을 사용하면 파일을 쉽게 가져올 수 있습니다. 어쩌면 나중에 클래스 이름을 재발 명할 수도 있지만 이제는 프레임 워크를 만드는 데 집중해야합니다. – Rasteril

답변

1

"Magic Methods"를 사용하고 싶습니다.이 특정 항목 (__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(); 
관련 문제