2018년 5월 22일 화요일

[PHP예제] 156 spl_autoload_register() 함수에 의한 오토로드


FileInfo.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
class FileInfo
{
  private $retCode;  // 줄 바꿈 코드 보존용

  // 파일을 읽고 조사하는 메소드
  public function readFile($file)
  {
    $this->retCode['CRLF'] = 0;  // 줄 바꿈 코드가 CRLF인 행 수
    $this->retCode['LF']   = 0;  // 줄 바꿈 코드가 LF인 행 수

    $fp = fopen($file, 'r');
    if (! is_resource($fp)) {
      die('파일을 열지 않음');
    }

    while (($line = fgets($fp)) !== false) {
      if (preg_match('/\r\n\z/', $line)) {
        $this->retCode['CRLF']++;
      } else {
        $this->retCode['LF']++;
      }
    }
    fclose($fp);
  }

  // 줄 바꿈 코드를 되돌려주는 메소드
  public function getRetCode()
  {
    if ($this->retCode['CRLF'] == 0 && $this->retCode['LF'] == 0) {
      return '';           // 줄 바꿈이 없는 경우
    } elseif ($this->retCode['CRLF'] == 0) {
      return 'LF';         // 모두 LF의 경우
    } elseif ($this->retCode['LF'] == 0) {
      return 'CRLF';       // 모두 CRLF의 경우
    } else {
      return 'CRLF & LF';  // CRLF와 LF가 함께 있는 경우
    }
  }
}


Counter.class.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php
// Counter 클래스를 정의합니다.
class Counter
{
// 정적 프로퍼티 $count를 선언합니다.
  public static $count = 0;

// 정적 메서드 increment()를 선언합니다.
  public static function increment()
  {
    static::$count++;
  }
  
// 정적 메서드 current()를 선언합니다.
  public static function current()
  {
    return static::$count;
  }
}
/* ?>종료 태그 생략 [레시피 001]*/


autoload.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
// 익명 함수를 사용하여 오토로드 함수를 등록함
spl_autoload_register(
  function ($classname)
  {
    // __DIR__은 이 소스 파일이 있는 디렉터리가 정의되는 매직 상수
    // 인수로서 전달된 클래스명을 바탕으로 '클래스명.class.php'를 찾음
    $filepath = __DIR__ . '/' . $classname . '.class.php';

    // 파일의 존재 확인을 진행
    if( is_readable($filepath) )
    {
      // 인수로 전달된 클래스명을 바탕으로 대응하는 파일을 읽음
      require $filepath;
    }
  }
);

spl_autoload_register(
  function ($classname)
  {
    // __DIR__은 이 소스 파일이 있는 디렉터리가 정의되는 매직 상수
    // 인수로서 전달된 클래스명을 바탕으로 '클래스명.class.php'를 찾음
    $filepath = __DIR__ . '/' . $classname . '.php';

    // 파일의 존재 확인을 진행
    if( is_readable($filepath) )
    {
      // 인수로 전달된 클래스명을 바탕으로 대응하는 파일을 읽음
      require $filepath;
    }
  }
);

156.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>spl_autoload_register() 함수에 의한 오토로드</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<?php
// 오토로드의 설정을 읽음
require './autoload.php';

echo "FileInfo 클래스를 인스턴스화 함: ";
$obj = new FileInfo();
$obj->readFile(__FILE__);
echo "<br>getRetCode() 메소드를 호출함: ";
echo $obj->getRetCode();
echo "<br>";
echo "Counter::current()를 호출함";
echo Counter::current();
?>
</div>
</body>
</html>


댓글 없음:

댓글 쓰기