메뉴 건너뛰기

프로그램언어

조회 수 283 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

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();
 
?>

 


 


하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved