php class 특강

2017. 3. 7. 07:28 from COMPUTER/php

php class 특강.


class :  클래스 이름을 정의한다. { }안에 클래스의 속성(멤버 변수)와 메소드를 정의한다.

클래스 명: 첫 글자가 문자나 밑줄로 시작해서 a ~ z, A ~ Z, 0 ~ 9, 언더라인( _ )이 붙는 127부터 255까지 길이. 클래스 명은 대문자로 시작하는 걸 추천.


new:

new 키워드는 클래스의 인스턴스를 만들기 위해 사용합니다. new 키워드를 사용하여 클래스를 초기화하면 해당 클래스의 변수나 메소드를 호출하기 위해 ->를 붙여 참조할 수 있습니다.


객체: 어떤 클래스를 사용해서 만들어진 것.

인스턴스: 객체가 메모리에 할당되어 실제 메모리를 차지하는 것.


예:

String str;

String 클래스를 사용하여 객체를 선언한 것. (아직은 str에 문자열이 할당되어 있지 않은 상태)

$str = new String("Hello world");

new 키워드를 사용하여 데이터가 생성됨. 이렇게 객체를 실제로 메모리에 할당하는 과정을 인스턴스화(instantiate)라고 한다.

즉 객체 $str에 "Hello world"라는 문자열을 할당해서 인스턴스화 하였고, 이렇게 인스턴스화 된 것을 인스턴스라고 부른다.


객체의 속성과 기능에 접근하기 위해선 -> 기호를 사용한다.

주의할 것은 클래스의 멤버 변수를 접근할 때 $기호를 붙이면 안 된다.


$this:

객체 안에서 작업할 때 자신을 참조할 경우 사용하는 예약 된 변수.

클래스 안에는 상수와 변수, 함수를 사용할 수 있고, 메소드가 객체 컨테스트에서 호출되는 경우 자기 자신의 객체를 나타내는 $this를 사용하여 호출한다.


ex #01)

<?php

    class test { }

    $instance01 = new test;

    $instance02 = new test;

?> 


ex #02)

<?php

    class test {

        function test() { }

        function profile($name) {

            echo "name : $name ";

        }

    }

    $instance = new test();

    $instance -> profile("Wicked");

    $instance -> profile("Miso");

    // 출력 name : Wicked name : Miso

 ?>


ex #03)

<?php

    class test {

        function profile($name) {

            echo "name : $name ";

        }

    }

    $instance01 = new test();

    $instance01 -> profile("Wicked");

    $instance02 = new test();

    $instance02 -> profile("Miso");

    // 출력 name : Wicked name : Miso

 ?> 


다음 예제처럼 객체를 참조하여 할당할 수도 있다.


ex #04)

<?php

    class test {

        function profile($name) {

            echo "name : $name ";

        }

    }

    $instance = new test();

    $a =& $instance;

    $a -> profile("Wicked");

    // 출력 : name : Wicked

 ?>


extends:

상속용 키워드.

서브 클래스는 부모 클래스의 모든 public과  ptorected로 선언된 것들을 상속 받게 된다. 단, 하나의 클래스만 상속할 수 있고 다중 상속은 할 수 없다. 그러나 다른 클래스의 내용을 계승하여 새로운 클래스를 만들어 원래의 클래스를 수정하지 않고 확장할 수 있다.

ex #01)

<?php

    class test {

        var $name = "Wicked";

    }

    /*

        test 클래스는 부모 클래스라 하고,

        상속 받은 Simple 클래스를 자식 클래스라 합니다.

        test 클래스로 simple 클래스를 확장한 것이므로

        test 클래스의 멤버 변수나 메소드도 사용할 수 있습니다.

    */


    class simple extends test {

        function profile() {

            echo "name : " . $this -> name;

        }

    }

    $a = new simple();

    $a -> profile();    // 출력 : name : Wicked

 ?>


ex #02)

<?php

    class test {

        var $name = "Wicked";

        function profile() {

            echo "name : ".$this -> name;

        }

    }

    class simple extends test {

        function output() {

            $this -> profile();

        }

    }

    $a = new simple();

    $a -> output();    // 출력 : name : Wicked

 ?>


public, protected, private 속성:

클래스의 멤버 변수를 속성이라 부르고, 속성을 정의하려면 public, protected, private 속성 중 하나의 키워드를 정의한 다음에 일반 변수를 선언합니다. 이 속성은 다음의 역할을 합니다.


public : 클래스 내부, 서브 클래스, 그리고 클래스 외부에서 사용할 수 있고, var를 선언하거나 생략하면 public 을 선언한 것으로 간주합니다. PHP5를 사용한다면 var을 사용하지 말라.

protected : 클래스 내부, 서브 클래스에서만 사용할 수 있습니다.

private : 클래스 내부에서만 사용할 수 있습니다.


ex #01)

<?php

    class test {

        // 속성은 php5.1.3부터 사용할 수 있다.

        public $name = "Wicked";

        public function profile() {

            echo "name : ".$this -> name;

        }

    }

    $a = new test();

    $a -> profile();

    // 출력 : name : Wicked

 ?>


ex #02)

<?php

    class test {

        // 속성은 php5.1.3부터 사용할 수 있다.

        public $name = "Wicked<br/>";

        public function profile() {

            echo "name : ".$this -> name;

        }

    }

    class simple extends test {

        public function output() {

            $this -> profile();

        }

    }

    $a = new test();

    $a -> profile();    // 출력 : name : Wicked

    $a = new simple();

    $a -> output();    // 출력 : name : Wicked

?>


다음은 protected 사용의 예.

ex #03)

<?php

    class test {

        // 속성은 php5.1.3부터 사용할 수 있습니다.

        protected $name = "Wicked<br/>";

        protected function profile() {

            echo "name : ".$this -> name;

        }

    }

    // 클래스 내부와 서브 클래스에서만 사용할 수 있게

    // 정의하였으므로 클래스 밖에서는 사용할 수 없습니다.    

    $a = new test();

    $a -> profile();    // 출력 :    

 ?>


const :

const 키워드를 정의하면 클래스 상수를 만들 수 있습니다. 다만, 값을 변경할 수 없는 상수를 클래스에 정의할 수 있지만 변수의 값에(self:: parent:: static:: 같은)키워드를 지정할 수 없습니다. -무슨 말이지?

class ClassName{

  const CONSTANT = 'CONSTANT VALUE';

}// $가 없다!

echo ClassName::CONSTANT; 처럼 사용.


ex #01)

<?php

    class test {

        // 속성은 php5.1.3부터 사용할 수 있다.

        const name = "Wicked<br/>";

        function profile() {

            echo "name-- : ".self::name;

        }

    }

    class simple extends test {

        function output() {

            $this -> profile();

        }

    }

    $a = new test();

    $a -> profile();    // 출력 :  name : Wicked

    $b = new simple();

    $b -> output();    // 출력 :  name : Wicked

    echo $a::name;    // 출력 :  Wicked

 ?>


ex #02)

<?php

    class test {

        const MY_NAME = "Wicked";

    }

    echo test::MY_NAME;

    // 출력 : Wicked

 ?>


생성자:

클래스가 객체로 만들어 질 때 자동으로 호출된다.

$obj = new ClassName(); //이때 클래스 내부에 

function __construct(){~~~~}

을 선언해주면 된다.

보통 객체 내부 초기화에 사용된다.

상속 시 부모의 생성자를 자동으로 호출하지는 않는다.

현재 생성자에서 수동 호출하도록 하라.

parent::__construct();


소멸자:

객체가 사라질 때 호출된다.

클래스 내부에 

function __destruct(){~~~~}

을 선언해주면 된다.

부모 소멸자도 자동 호출되지 않으니, 수동으로....

 parent:: __destruct();

실제 사용하다가 버그 때문에 이상 동작한다는 이야기가 있다. 사용에 주의하라.


ex #01)

<?php

    class test {

        var $name = null;

        var $email = null;

        var $age = null;

        function __construct($a, $b, $c) {

            $this -> name = $a;

            $this -> email = $b;

            $this -> age = $c;

        }

        function profile() {

            printf("name %s(%s) %s<br/>", $this -> name, $this -> age, $this -> email);

        }

    }

    $a = new test("Wicked", "10", "id01");

    $b = new test("Miso", "20", "id02");

    $c = new test("Hayate", "30", "id03");

    $a -> profile();

    $b -> profile();

    $c -> profile();

    /*

        출력 :

            name : Wicked(id01) 10

            name : Miso(id02) 20

            name : Hayate(id03) 30

    */

?>


static:

static 키워드는 객체의 인스턴스를 생성하지 않고도 호출할 수 있게 해줍니다. 보통 멤버 변수를 사용하기 위해 $this 와 -> 를 사용해야 하지만 static 키워드가 선언된 메소드는 그럴 필요 없이 :: 로 접근할 수 있습니다.

static 키워드로 선언된 메소드는 반대로 $this 와 -> 로 엑세스할 수 없고, 메소드 내부에서도 이용할 수 없지만 static 이 선언된 변수를 내부에서 이용하려면 self를 이용하면 됩니다.

 static이 아닌 메소드를 정적으로 호출하면 E_STRICT 레벨의 경고가 발생합니다.


TIP : php5.3부터 변수를 사용하여 클래스를 참조할 수 있지만 변수의 값에 (self:: parent:: static:: 같은) 키워드를 지정할 수 없습니다.-무슨 말?

 ex #01)

<?php

    class test {

        static $name = "Wicked";

        static $email = "yinglong200@me.com";

        static $age = "28";

        public static function profile() {

            printf("name %s(%s) %s<br/>", self::$name, self::$age, self::$email);

        }

    }

    echo test::$name;

    // 출력 Wicked

    test::profile();

    // 출력 : name Wicked(28) yinglong200@me.com

?>


php5.3부터 변수를 사용하여 클래스를 호출할 수 있습니다.

ex #02)

<?php

    class test {

        static $name = "Wicked";

        static $email = "yinglong200@me.com";

        static $age = "28";

        public static function profile() {

            printf("name %s(%s) %s<br/>", self::$name, self::$age, self::$email);

        }

    }

    $classname = "test";

    echo $classname::$name;//변수를 사용할 수 있다는 말이 이건가?

    // 출력 Wicked

    $classname::profile();

    // 출력 : name Wicked(28) yinglong200@me.com

?>


self(또는 parent) 키워드

parent::

부모 클래스로 접근할 수 있다.

self(또는 parent) 키워드를 사용하면 정적 상속 컨텍스트에서 호출 클래스를 참조할 수 있다. self 키워드는 해당 메소드가 정의된 클래스 이름을 가져 올 수 있고, get_called_class()함수를 사용하면 클래스 이름을 문자열로 가져온다.

static:: 의 차이는 정적 속성만 참조할 수 없다는 점을 제외하면 동일하고, parent:: self:: 같은 키워드를 사용하여 요청자의 정보를 전송할 수 있습니다.

ex #01)

<?php

    class test {

        public static function who() {

            echo __CLASS__; //이건 뭐지?

        }

        public static function output() {

            self::who();

        }

    }

    class simple extends test {

        public static function who() {

            //...

        }

    }

    simple::output();

    // 출력 : test

?>

ex #02)

<?php

    class test {

        function __construct($child) {

            echo "I Was called by " . $child . "<br/>";

        }

    }

    class simple extends test {

        function __construct() {

            parent::__construct(__CLASS__);//언더라인은 뭐지?=>생성자 또는 소멸자를 표기할 때 사용되는 방법.

        }

        function output() {

            echo "I am class " . __CLASS__;

        }

    }

    $a = new simple;

    // 출력 : I was called by simple

    $a -> output();

    // 출력 : I am class simple

?>


final:

final 키워드는 php5.0부터 사용할 수 있습니다. final 키워드를 클래스나 메소드에 정의하면 정의된 메소드는 자식 메소드에 재정의 할 수 없고, 클래스 자체를 final로 정의된 경우 이 클래스를 상속에 사용할 수 없습니다. public과 같은 속성에 final로 선언할 수도 없습니다.

ex #01)

<?php

    final class test {

        public function profile() {

            echo "name : Wicked";

        }

    }

    class simple extends test {

        function output() {

            $this -> profile();

        }

    }

    $a = new simple();

    $a -> output();

    // 출력 : Fatal error: Class simple may not inherit from final class (test) in ...\ex19.php on line 16

?>


ex #02)

<?php

    final class test {

        public function profile() {

            echo "name : Habony";

        }

    }

    $a = new test();

    $a -> output();

    // 출력 : name : Habony

?>


범위 정의 연산자 더블 콜론( :: )

범위 정의 연산자 더블 콜론(::)은  static, 상수, 재정의 된 클래스의 속성과 메소드에 액세스할 때 사용합니다. 클래스 내부에서 액세스하고자 할 때는 self:: 나 parent::, static::를 사용하면 됩니다.

ex #01)

<?php

    class test {

        const CONST_VALUE = 'Wicked';

    }

    echo test::CONST_VALUE;

    // 출력 : Wicked

?>


ex #02)

<?php

    class test {

        const CONST_VALUE = 'my name is';

    }

    class simple extends test {

        public static $my_static = 'Wicked;';

        public static function my_name() {

            echo parent::CONST_VALUE."&nbsp;";

            echo self::$my_static."<br/>";

        }

    }

    // php5.3부터 변수를 사용하여 클래스를 참조할 수 있습니다.

    $classname = 'simple';

    echo $classname::my_name();

    // 출력 : my name is Wicked;

    simple::my_name();

    // 출력 : my name is Wicked;


Tip : php5.3부터 변수를 사용하여 클래스 이름을 정의할 수 있다.

ex #01)

<?php

    class test {

        // 클래스 안의 변수를 멤버 변수라 부른다.

        var $name = "Wicked"; //사실 var는 비추. public 추천.

        var $email = "yinglong200@me.com";

        function display() { //클래스안의 함수는 메쏘드라고 한다.

            echo $this -> name."<br/>\n"; //이런 표현을 잘 보자.

            echo $email; //여기는 에러가 난다.

        }

/*문자열의 끝에서 다음 줄로 넘어가는 줄 바꿈을 하는 방법.

"\n" 이라는 이스케이프 문자는 PHP 내부에서의 줄 바꿈이고, 실제 브라우저에서는 "\n"으로는 줄 바꿈이 되지 않기에, "<br/>" 이라는 HTML 줄 바꿈 태그를 같이 출력해 주어야 함. 따라서 최종적으로"<br/>\n"를 사용해서 줄 바꿈을 한다.

*/

    }

    $method = new test;

    $method -> display();

    // 출력 : Wicked

?>


ex #02)

<?php

    class test {

        var $name = "Wicked";

        var $email = "yinglong200@me.com";

        function Cat() {

            echo $this -> name."&nbsp;"; //$표기가 name에서 빠진다.

            echo $this -> email;

        }

        function display() {

            $this -> Cat(); //자신의 함수 Cat()을 부른다.

        }

    }

    $method = new test;

    $method -> display();

    // 출력 : Wicked yinglong200@me.com

?>

'COMPUTER > php' 카테고리의 다른 글

5. 배열 변수 -php-  (0) 2017.03.11
4. for문 -php-  (0) 2017.03.10
3. 연산자. -php-  (0) 2017.03.10
2. post 방식. -php-  (0) 2017.03.09
1. php의 기본. -php-  (0) 2017.03.08
Posted by star story :

Snippet :: Code View :: "+location.href+'
'+b+"

");top.consoleRef.document.close()}$(".snippet-container").each(function(b){$(this).find("a.snippet-text").click(function(){var d=$(this).parents(".snippet-wrap").find(".snippet-formatted");var c=$(this).parents(".snippet-wrap").find(".snippet-textonly");d.toggle();c.toggle();if(c.is(":visible")){$(this).html("html")}else{$(this).html("text")}return false});$(this).find("a.snippet-window").click(function(){var c=$(this).parents(".snippet-wrap").find(".snippet-textonly").html();a(c);$(this).blur();return false})});$(".snippet-toggle").each(function(b){$(this).click(function(){$(this).parents(".snippet-container").find(".snippet-wrap").toggle()})})});