programing

디렉토리에서 모든 PHP 파일을 포함()하려면 어떻게 해야 합니까?

bestcode 2023. 1. 1. 11:13
반응형

디렉토리에서 모든 PHP 파일을 포함()하려면 어떻게 해야 합니까?

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

즉, 다음 대신:

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

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

include('classes/*');

특정 클래스에 대해 약 10개의 서브클래스의 컬렉션을 포함할 수 있는 좋은 방법을 찾을 수 없었던 것 같습니다.

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

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;
        }
    }
}

오래된 포스트인 건 알지만...클래스를 포함하지 마십시오. 대신 __autoload를 사용합니다.

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

$user = new User();

그리고 아직 포함되지 않은 새 클래스를 호출할 때마다 php는 __autoload를 자동으로 실행하여 포함시킵니다.

이것은 카스텐의 코드를 수정한 것일 뿐이다

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

include_all_php("my_classes");

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 문서에서 권장하는 내용:클래스 자동 로드

set_include_path를 사용할 수 있습니다.

set_include_path('classes/');

http://php.net/manual/en/function.set-include-path.php

<?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"); 
}

파일 간에 종속성이 없는 경우...다음은 모든 서브디르에 모든 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');

디렉토리 및 그 서브 디렉토리에 모두 포함시키려면 , 다음의 순서에 따릅니다.

$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;
}

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

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

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

할 수 , php 파일 목록은 정의할 수 .$thisclass = new thisclass();

모든 파일을 얼마나 잘 처리할 수 있을까요?이걸로 약간의 속도 저하가 있을지는 모르겠습니다.

readdir() 함수를 사용하여 파일을 루프하여 포함하는 것이 좋습니다(이 페이지의 첫 번째 예 참조).

그런 목적으로 도서관을 이용해 보세요.

그것은 내가 구축한 것과 같은 아이디어에 대한 간단한 구현입니다.여기에는 지정된 디렉터리 및 하위 디렉터리 파일이 포함됩니다.

모두 포함

터미널 [cmd] 경유로 설치

composer install php_modules/include-all

또는 패키지의 종속성으로 설정합니다.json 파일

{
  "require": {
    "php_modules/include-all": "^1.0.5"
  }
}

사용.

$includeAll = requires ('include-all');

$includeAll->includeAll ('./path/to/directory');

이것은 PHP > 7.2에서 PHP 8까지를 나타내는 늦은 답변입니다.

OP는 제목에 수업에 대해 묻지 않지만, 그의 표현에서 그가 수업을 포함시키고 싶어한다는 것을 알 수 있습니다.(다만, 이 방법은 네임스페이스에서도 사용할 수 있습니다).

require_를 사용하여 한 번의 수건으로 모기 3마리를 죽인다.

  • 먼저 파일이 존재하지 않는 경우 로그 파일에 오류 메시지 형식으로 의미 있는 펀치를 얻을 수 있습니다.이는 디버깅 시 매우 유용합니다.(include는 그다지 상세하지 않을 수 있는 경고만 생성합니다.)
  • 클래스가 포함된 파일만 포함합니다.
  • 클래스를 두 번 로드하지 않도록 합니다.
spl_autoload_register( function ($class_name) {
    require_once  '/var/www/homepage/classes/' . $class_name . '.class.php';
} );

이것은 수업과 함께 작동될 것이다.

new class_name;

또는 네임스페이스(예: ...)

use homepage\classes\class_name;

답변은 다른 질문에서 넘겨졌다.포함된 파일에 모든 변수를 로드하기 위한 도우미 기능과 함께 도우미 기능 사용 제한에 대한 추가 정보가 포함되어 있습니다.

PHP에는 기본 "폴더에서 모두 포함"이 없습니다.하지만, 그것을 성취하는 것은 그리 복잡하지 않다.의 경로를 글로벌하게 설정할 수 있습니다..php파일 및 파일을 루프에 포함합니다.

foreach (glob("test/*.php") as $file) {
    include_once $file;
}

이 답변에서 저는include_once파일을 포함하기 위해.부담없이 변경해 주세요include,require또는require_once필요에 따라서

이 기능을 단순한 도우미 기능으로 전환할 수 있습니다.

function import_folder(string $dirname) {
    foreach (glob("{$dirname}/*.php") as $file) {
        include_once $file;
    }
}

파일에 스코프에 의존하지 않는 클래스, 함수, 상수 등이 정의되어 있는 경우, 이것은 예상대로 동작합니다.다만, 파일에 변수가 있는 경우는, 다음과 같이 「수집」할 필요가 있습니다.get_defined_vars()함수에서 돌려보낼 수 있습니다.그렇지 않으면 원래 범위로 Import되지 않고 함수 범위로 "분실"됩니다.

함수에 포함된 파일에서 변수를 가져와야 하는 경우 다음을 수행할 수 있습니다.

function load_vars(string $path): array {
    include_once $path;
    unset($path);
    return get_defined_vars();
}

이 함수는 이 함수와 조합할 수 있습니다.import_folder는 포함된 파일에 정의된 모든 변수를 포함하는 배열을 반환합니다.여러 파일에서 변수를 로드하는 경우 다음을 수행할 수 있습니다.

function import_folder_vars(string $dirname): array {
    $vars = [];
    foreach (glob("{$dirname}/*.php") as $file) {

        // If you want to combine them into one array:
        $vars = array_merge($vars, load_vars($file)); 

        // If you want to group them by file:
        // $vars[$file] = load_vars($file);
    }
    return $vars;
}

위의 경우 사용자의 취향에 따라(필요에 따라 주석/주석 없음) 포함된 파일에 정의된 모든 변수를 단일 배열로 반환하거나 정의된 파일에 따라 그룹화합니다.

마지막 메모:필요한 것이 클래스 로드뿐이라면 를 사용하여 필요에 따라 자동 로드하는 것이 좋습니다.자동 로더를 사용하는 것은 파일 시스템을 구조화하고 클래스 및 네임스페이스에 일관되게 이름을 붙이는 것을 전제로 하고 있습니다.

디렉토리에 파일을 포함할 함수()를 쓰지 마십시오.변수 범위가 손실될 수 있으며 "global"을 사용해야 할 수 있습니다.그냥 파일만 다시 돌려봐.

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

언급URL : https://stackoverflow.com/questions/599670/how-to-include-all-php-files-from-a-directory

반응형