'require'에 해당되는 글 1건

  1. 2011.05.16 php 코드 재활용과 클래스 1
반응형
I. require 와 include
    1. 다른 파일을 불러온다. HTML 태그, php 함수, php 클래스 등이다.
    2. require() 는 실패했을 경우 치명적인 오류를 내지만 include() 는 가벼운 경고만 낸다.
    3. require_once()와 include_once() 는 라이브러리 파일을 두 번 이상 포함시키는 일을 막아준다.
        그러나 require()나 include() 보다 속도가 느리다. 
    4. php 문은 파일 확장자가 .html 이거나 .php 등일 때에만 스크립트 언어로 처리되어 실행.
    5. require로 불러들일 파일의 확장자 이름에 .inc와 같은 특별한 규칙을 두어 작성하는 것도 좋은 방법
        단, 이런 문서를 웹 문서 트리 안에 저장할 때에는 사용자들이 직접 접근 하지 못하도록 주위 (패스워드 등) 
        php 환경설정에서 아래와 같이 디렉토리를 웹 문서 디렉토리로 설정하고 추가로 config 설정파일은
        php 웹 문서가 아닌 디렉토리로 지정할 수 있다.(/Library/WebServer/php/includes)
        예) include_path = ".:/Library/WebServer/php/includes:/Library/WebServer/Documents"

II. 참조 전달 방법
    1. & 를 이용하면 참조로 전달 할 수 있다.
function increment(&$value, $amount = 1) {
    $value = $value + $amount;

III. 클래스 만들기
    1. 생성자와 소멸자
        - 생성자는 __construct() 라는 특별한 이름으로 파라미터를 가지며 생성할 수 있다.
        - 소멸자는 __destruct() 라는 이름으로 만들며 파라미터를 가지지 못한다.
 
    2. 클래스 속성
        - 접근자가 생략되면 모두 public 이다.
        - 클래스 속성의 접근자는 private 으로 하고 __set(), __get() 으로 속성에 접근한다.
        - 자기 자신의 인스턴스는 $this 로 접근한다.

class Point {

    private $x;

    private $y;

    public function __construct($x, $y) {

        $this->x = $x;

        $this->y = $y;

    }

    public function __get($name) {

        return $this->$name;

    }

    public function __set($name, $value) {

        $this->$name = $value;

    }

    public function display() {

        print("\$this->x = " . $this->x . "<br/>");

        print("\$this->y = " . $this->y . "<br/>");

    } 

}

$point = new Point(3, 5);

print($point->x);         // 3

print($point->y);         // 5

$point->x = 7;

print($point->x);         // 7

$point->display(); 


    3. 클래스 상속
        - 부모의 클래스는  parent 키워드를 이용한다.

class Rectangle extends Point {

    private $width;

    private $height;


    public function __construct($x, $y, $width, $height) {

        parent::__construct($x, $y);

        $this->x = $x;

        $this->y = $y;

    }

}

$rectangle = new Rectangle(10, 20, 100, 200);

print($rectangle->x);   // 10

 
    4. 인터페이스
        - 인터페이스는 interface 키워드를 사용한다.
        - 구현은 implements 로 한다.

interface Displayable {

    public function display();

}

class WebPage implements Displayable {

    public function display() {

        print("Hello World!! <br/>");

    }

}

$page = new WebPage();

$page->display();


    5. 클래스의 상수 및 정적 메소드 
        - 상수는 const 키워드를 사용하고 :: 연산자로 접근한다.
        - 정적 메소드는 static 키워드를 사용하고 :: 연산자로 접근한다.

class Math {

    const pi = 3.14159;

    public static function squared($input) {

        return $input * $input;

    }

}

print("Math::pi = " . Math::pi . "<br/>");

print("Math::squared(8) = " . Math::squared(8) . "<br/>");


    6. 클래스 타입 hinting
        - 클래스의 특정 타입을 파라미터 전달 시에 전달할 수 있다.
function check_hint(Point $object) {
    // ...

    7.  추상 클래스
        - abstract 키워드를 사용한다.

abstract class A {

    public abstract function operationX($param1, $param2);

}

class ConcreteA extends A {

    public function operationX($param1, $param2) {

        return $param1 + $param2;

    }

}

$a = new ConcreteA();

print($a->operationX(3, 4) . "<br/>");


    8. 메소드 오버로딩
        - __call() 메소드를 이용하여 오버로딩을 구현한다.
        - 첫번째 전달인자는 호출되는 메소드이고, 두번째 전달인자는 파라미터로 넘길 파라미터 배열이다.
public function __call($method, $param) {
    if ($method == "display") {
        if (is_object($p[0])) {
            $this->displayObject($p[0]);
        } else if (is_array($p[0])) {
            $this->displayArray($p[0]);
        } else {
            $this->displayScalar($p[0]);
        }
    }
}

$object = new Overload();
$object->display(array(1, 2, 3));
$object->display('cat'); 

    9. 클래스 자동 import
        - __autoload() 함수를 이용하여 자동으로 include 할 수 있다.
        - 이 함수는 클래스 메소드가 아니라 독립된 함수이다.
        - 아래는 클래스 파일과 같은 파일명을 읽어 들이는 예제이다.
function __autoload($name) {
    include_once $name . ".php";

    10. Reflection API
require_once("config.inc");

$class = new ReflectionClass("Point");
print("<pre>" . $class . "</pre>"); 


반응형
Posted by seungkyua@gmail.com
,