플밍

부모클래스에서 자식클래스 이름 및 파일명 구해오기 본문

프로그래밍/PHP

부모클래스에서 자식클래스 이름 및 파일명 구해오기

너구리안주 2014. 6. 14. 13:52



자식클래스에서 중복되는 코드를 부모클래스에서 구현하고자 할때

자식클래스의 정보가 필요할때가 있습니다.


#ads_1

아래코드와 같이 사용하시면 됩니다.

팩토리 패턴이나 추상메소드를 사용할때 유용하게 사용할 수 있습니다.

※ PHP 5 이상만 가능합니다.


animal.php : 부모클래스

<?php
abstract class Animal{
   
    protected $ch_class;    //자식 클래스 이름
    protected $ch_path;        //자식 클래스의 파일경로
   
    public function __construct(){
        $this->setChildInfo();
    }
   
    public function setChildInfo(){
        $ref = new ReflectionObject($this);
        $this->ch_class = $ref->getName();
        $this->ch_path = $ref->getFileName();
       
    }
   
    public function printInfo(){
        echo 'Child Class: '.$this->ch_class.'<br>';
        echo 'Child Path: '.$this->ch_path.'<br>';
    }
}


#ads_2

dog.php : 자식클래스

<?php

include 'animal.php';

class Dog extends Animal{
   
}


test.php : 테스트 파일

<?php

include 'dog.php';

$d = new Dog();
$d->printInfo();


<< 결과 >>

Child Class: Dog
Child Path: /home/test/public_html/dog.php

#ads_3


Comments