본문 바로가기
PHP 박살내기/PHP

[PHP기초] 클래스 맴버 만들기(static)

by 인생여희 2017. 9. 6.
반응형

클래스 맴버 만들기(static)


static.php

<?php
//클래스 변수
//고정된 이라는뜻
// static : 모든 인스턴스가 공유하는 변수 만들기!!
//static 변수는 class 명으로 바로 접근할 수 있다.(instance 즉 객체를 만들지 않고 접근가능하다.)


class Person{

private $name; //다른 객체가 접근할 수 없다. 즉 공통으로 사용할 수 없다.

private $count = 0;

//생성자: 객체가 생성될때 필요한 값을 셋팅한다.
function __construct($name){
$this->name = $name;
$this->count = $this->count +1;
}

function enter(){
echo "<h1>Enter ".$this->name." {$this->count} th</h1><br>";
}

}

$p1 = new Person('abcnt');
$p1 ->enter();


$p2 = new Person('하하하');
$p2 ->enter();

$p1 = new Person('호호호');
$p1 ->enter();


?>



static2.php

<?php
//클래스 변수
//고정된 이라는뜻
// static : 모든 인스턴스가 공유하는 변수 만들기!!
//static 변수는 class 명으로 바로 접근할 수 있다.(instance 즉 객체를 만들지 않고 접근가능하다.)


class Person{


//인스턴스 변수
private $name; //다른 객체가 접근할 수 없다. 즉 공통으로 사용할 수 없다.


//클래스 변수 // 모든 인스턴스가 공유한다!!
//클래스 변수에는 self::를 사용한다.
private static $count = 0;

//생성자: 객체가 생성될때 필요한 값을 셋팅한다.
function __construct($name){
$this->name = $name;
self::$count = self::$count +1;
}

function enter(){
echo "<h1>Enter ".$this->name." ".self::$count." th</h1><br>";
}

//클래스 이름으로 호출되려면 static을 호출해야 한다.
static function getCount(){

//클래스 변수에는 self를 사용한다.
return self::$count;
}

}


$p1 = new Person('abcnt');
$p1 ->enter();

$p2 = new Person('하하하');
$p2 ->enter();

$p1 = new Person('호호호');
$p1 ->enter();

//클래스 변수 호출
echo Person::getCount();

?>


반응형

댓글