디렉토리에서 모든 PHP 파일을 포함시키는 방법은 무엇입니까?


230

PHP에서 스크립트 디렉토리를 포함시킬 수 있습니까?

즉 :

include('classes/Class1.php');
include('classes/Class2.php');

다음과 같은 것이 있습니까?

include('classes/*');

특정 클래스에 대해 약 10 개의 서브 클래스 모음을 포함시키는 좋은 방법을 찾지 못했습니다.

답변:


437
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}

4
include ()를 사용하여 깔끔하게 보이는 방법이 있다고 생각했습니다. 그러나 이것은 잘 될 것입니다. 모두 감사합니다.
— occhiso

5
구성 파일을 사용하여 적절한 모듈 시스템을 만들지 만 모든 것을 포함하는 것 보다 훨씬 유연하기 때문 입니다. :-)
— staticsan

3
주의, 현재 디렉토리에 파일을 포함시키는 경우에만 작동합니다. get_include_path ()를 반복 할 수는 있지만 지루합니다.
— nalply

20
이 메소드는 기본 클래스를 확장하는 클래스가 필요할 때 좋지 않습니다. 예를 들어 BaseClass가 AFTER ExtendedClass 배열에 표시되면 작동하지 않습니다!
— Carmageddon

2
@nalply는 get_include_path()여전히 로딩 순서를 자동으로 결정할 수 없습니다 (확장 된 클래스 이후에 기본 클래스가로드되어 오류가 발생할 수 있음)
— Raptor

50

다음은 PHP 5의 여러 폴더에서 많은 클래스를 포함하는 방법입니다. 클래스가있는 경우에만 작동합니다.

/*Directories that contain classes*/
$classesDir = array (
    ROOT_DIR.'classes/',
    ROOT_DIR.'firephp/',
    ROOT_DIR.'includes/'
);
function __autoload($class_name) {
    global $classesDir;
    foreach ($classesDir as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once ($directory . $class_name . '.php');
            return;
        }
    }
}

3
이 질문은 디렉토리의 모든 것을 포함하는 것이 중요하기 때문에 관련이 없습니다. 일반적으로 이것은 다른 디렉토리에 있습니다. 예를 들어 BE 디렉토리에 정의 된 DataClass와 BL 디렉토리에 정의 된 BL.class.php.
— Carmageddon

1
글로벌을 사용하는 것은 해결책이 아닙니다
— Peter

여기에 표시된 것과 같은 맞춤형 자동 로딩 솔루션 대신 자동 로딩이 필요한 경우 composer ( getcomposer.org )를 사용 하는 것이 좋습니다.
— Kelt

32

나는 이것이 오래된 게시물이라는 것을 알고 있지만 클래스를 포함하지 마십시오 ... 대신 __autoload

function __autoload($class_name) {
    require_once('classes/'.$class_name.'.class.php');
}

$user = new User();

그런 다음 아직 포함되지 않은 새 클래스를 호출 할 때마다 PHP는 자동 실행 __autoload를 포함하고 자동으로 포함합니다


1
PHP7.2.0부터는 게시되었을 때 확실한 답 이었지만이 방법은 더 이상 사용되지 않으며 사용해서는 안됩니다. 대신 spl_autoload_register를 사용 하십시오 .
— frozenjakalope

1
목적이 수업을 포함하는 경우 더 나은 답변입니다.
— Blackbam


20

이것은 Karsten의 코드를 수정 한 것입니다.

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}

include_all_php("my_classes");

12
허용되는 답변과 관련된 내용은 추가되지 않습니다.
— moopet

이것이 실제로 어떤 이유로 든 작동하는 유일한 코드였습니다.
— 조셉 Astrahan

19

2017 년에이를 수행하는 방법 :

spl_autoload_register( function ($class_name) {
    $CLASSES_DIR = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR;  // or whatever your directory is
    $file = $CLASSES_DIR . $class_name . '.php';
    if( file_exists( $file ) ) include $file;  // only include if file exists, otherwise we might enter some conflicts with other pieces of code which are also using the spl_autoload_register function
} );

PHP 문서에서 권장하는 위치 : 자동 로딩 클래스


이것은 autoload아직로드되지 않은 클래스의 객체를 만들려고 할 때만 작동 하기 때문에 질문에 대답하지 않습니다 .
— 대부


1

디렉토리 및 서브 디렉토리에 모두를 포함 시키려면 다음을 수행하십시오.

$dir = "classes/";
$dh  = opendir($dir);
$dir_list = array($dir);
while (false !== ($filename = readdir($dh))) {
    if($filename!="."&&$filename!=".."&&is_dir($dir.$filename))
        array_push($dir_list, $dir.$filename."/");
}
foreach ($dir_list as $dir) {
    foreach (glob($dir."*.php") as $filename)
        require_once $filename;
}

알파벳 순서를 사용하여 파일을 포함한다는 것을 잊지 마십시오.


3
... 잘못 "는 알파벳 순서를 사용하는 것을 잊지 마세요" The entries are returned in the order in which they are stored by the filesystem.- php.net/manual/en/function.readdir.php
— NemoStein

1
파일이 서로 종속되어 있고 순서가 종속성과 일치하지 않으면 작동하지 않을 수 있습니다.
— Amanuel Nega

1

한 번에 각 클래스를 정의하지 않고 많은 클래스를 포함하려는 경우 다음을 사용할 수 있습니다.

$directories = array(
            'system/',
            'system/db/',
            'system/common/'
);
foreach ($directories as $directory) {
    foreach(glob($directory . "*.php") as $class) {
        include_once $class;
    }
}

이렇게하면 클래스가 포함 된 PHP 파일에서 클래스를 정의 할 수 있습니다. $thisclass = new thisclass();

모든 파일을 얼마나 잘 처리합니까? 이것으로 약간의 속도 저하가 있을지 확실하지 않습니다.


1

파일간에 의존성 이 없다면 ... 모든 하위 디렉토리에 모든 PHP 파일을 포함하는 재귀 함수입니다.

$paths = array();

function include_recursive( $path, $debug=false){
  foreach( glob( "$path/*") as $filename){        
    if( strpos( $filename, '.php') !== FALSE){ 
       # php files:
       include_once $filename;
       if( $debug) echo "<!-- included: $filename -->\n";
    } else { # dirs
       $paths[] = $filename; 
    }
  }
  # Time to process the dirs:
  for( $i=count($paths)-1; $i>0; $i--){
    $path = $paths[$i];
    unset( $paths[$i]);
    include_recursive( $path);
  }
}

include_recursive( "tree_to_include");
# or... to view debug in page source:
include_recursive( "tree_to_include", 'debug');

1
<?php
//Loading all php files into of functions/ folder 

$folder =   "./functions/"; 
$files = glob($folder."*.php"); // return array files

 foreach($files as $phpFile){   
     require_once("$phpFile"); 
}

코드에 더 많은 설명을 추가하십시오. 특히이 질문에 이미 많은 답변이 있습니다.
— Nico Haase


-1

디렉토리에 파일을 포함시키기 위해 function ()을 작성하지 마십시오. 변수 범위를 잃을 수 있으며 "전역"을 사용해야 할 수도 있습니다. 파일을 반복하십시오.

또한 포함 된 파일에 아직 포함되지 않은 다른 파일에 정의 된 다른 클래스로 확장 될 클래스 이름이있는 경우 문제가 발생할 수 있습니다. 그러니 조심해.


2
"가변 범위를 잃다"는 무슨 뜻입니까?
— piyush

3
재사용하거나 항상 코드를 "자체 문서화"로 만들려면 항상 함수를 사용해야합니다. "글로벌 스코프"문제는 청각 문제라고 생각합니다. "전역 범위"를 사용할 때마다 코드를 피하기 위해 코드를 다시 작성하는 것에 대해 진지하게 생각하고 싶습니다.
— Stave Escura
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.