클래스의 선언 (클래스의 정의)

<?php
class SimpleClass{
    // 프로퍼티 정의
    public $var = '변수';

    // 메서드 정의
    public function displayVar() {
        echo $this->var;
        // echo $var; 으로 사용할 수 없습니다.
    }
}
?>

클래스의 생성 및 사용

<?php
$sc1 = new SimpleClass;
$sc1->displayVar();
echo $sc1->var;
?>

클래스의 생성 및 사용2

<?php
$class_name = "SimpleClass";
$sc2 = new $class_name;
$sc2->displayVar();
echo $sc2->var;
?>

프로퍼티 (properties)

클래스 내부에 존재하며 클래스의 속성값 (attribute)을 갖음

<?php
class PropertiesClass{
	public $dynamic_var = "동적 프로퍼티";
	public static $static_var = "정적 프로퍼티";
}

$pc = new PropertiesClass();
echo $pc->dynamic_var;
echo PropertiesClass::$static_var;
?>

동적, 정적 프로퍼티의 동작

<?php
class StudentClass{
	public static $school = "00대학교";
	public $name = "홍길동";

	public function introduce(){
		echo "제 이름은".$this->name."입니다."." 저는".StudentClass::$school."학생 입니다.<br />";
	}
}
echo "<hr/>";
$student1 = new StudentClass();
$student2 = new StudentClass();
$student3 = new StudentClass();
$student1->name = "김철수";
$student2->name = "나영희";
$student3->name = "박영수";

StudentClass::$school = "계원 예술 대학교";

$student1->introduce();
$student2->introduce();
$student3->introduce();

?>

클래스의 상속 (extends)

<?php
class ExtendClass extends SimpleClass{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

클래스 생성자 (construct)

  • 클래스 생성시에 자동으로 호출되는 메서드. 클래스의 초기화 등을 담당한다.
<?php
class ConstructClass{
	function __construct(){
		echo "클래스가 새로 생성 되었습니다";
	}
}
$cc = new ConstructClass();
?>

클래스 소멸자 (destruct)

  • 클래스의 소멸시에 자동으로 호출되는 메서드.
<?php
class DestructClass{
	function __destruct(){
		echo "클래스가 소멸 되었습니다";
	}
}
$cc = new DestructClass();
?>

프로퍼티와 메서드의 가시성

{| class=”wikitable” |- | public || 어느곳에서든지 접근 가능 |- | protected || 클래스 자신이나 상속된 클래스, 부모 클래스에서만 접근 가능 |- | private || 해당 클래스 내에서만 접근 가능 |}

<?php
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
?>