테스트 사이트 - 개발 중인 베타 버전입니다

[클래스] 여러 종류의 객체를 하나의 배열로 다루기

· 11년 전 · 1002

class Buyer {             

var $money = 1000,

$cart = array(), // 구입한 제품을 저장하기 위한 배열 

$i = 0; // Product배열 cart에 사용될 index 

 

function buy(Product $p) { 

if ($p->price > $this->money) {

println('잔액이 부족하여 ' . $p . '를 살수 없습니댜.');

return;

}

$this->money -= $p->price;

$this->add($p);

/*

            가진 돈과 물건의 가격을 비교해서 가진 돈이 적으며 종료한다.

            가진 돈이 충분하면, 제품의 가격을 가진 돈에서 빼고

            장바구니에 구입한 물건을 담는다. (add메서드 호출)

*/

 

function add(Product $p) {

$this->cart[$this->i] = $p;

$this->i++;

/*

  물건을 장바구니(cart)에 저장한다. 그리고 i의 값을 1 증가시킨다.

*/

} // add(Product p)

 

function summary() {

$itemList = '';

$sum = 0;

for ($i=0; $i<count($this->cart); $i++) {

$this->itemList .= $this->cart[$i] . ',';

$this->sum += $this->cart[$i]->price;

}

 

println('구입한 물건 : ' . $this->itemList);

println('사용한 금액 : ' . $this->sum);

println('남은 금액 : ' . $this->money);

/*

장바구니에 담긴 물건들의 목록을 만들어 출력한다.

장바구니에 담긴 물건들의 가격을 모두 더해서 출력한다.

물건을 사고 남은 금액(money)를 출력한다.

*/

} // summary()

 

class Product {

var $price; // 제품의 가격

 

function __construct($price) {

$this->price = $price;

}

}

 

class Tv extends Product {

function __construct() { 

Parent::__construct(100); 

}

 

public function __toString() {

        return 'Tv'; 

    }

}

 

class Computer extends Product {

function __construct() { 

Parent::__construct(200); 

}

 

public function __toString() {

return 'Computer';

}

}

 

class Audio extends Product {

function __construct() { 

Parent::__construct(50); }

 

public function __toString() {

return 'Audio'; 

}

}

 

$b = new Buyer();

$b->buy(new Tv());

$b->buy(new Computer());

$b->buy(new Tv());

$b->buy(new Audio());

$b->buy(new Computer());

$b->buy(new Computer());

$b->buy(new Computer());

 

$b->summary();

 

// 줄바꿈 출력

function println($arg) {

echo $arg.'<br />';

/* 출력

​ 잔액이 부족하여 Computer를 살수 없습니댜.

구입한 물건 : Tv,Computer,Tv,Audio,Computer,Computer,
사용한 금액 : 850

남은 금액 : 150 

*/

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
20318
20317
20316
20315
20314
20313
20312
20311
20310
20309
20308
20307
20306
20303
20302
20301
20300
20299
20298
20297
20296
20295
20294
20293
20292
8222
20291
20290
20289
20288
20287
20286
20285
20284
20283
20282
20281
20280
20276
20275
20274
20273
8216
20272
20271
20270
20269
20268
20267
20265
20264
20263
20262
20261
20259
20258
20257
20256
20255
20254
20253
20252
20251
20250
20249
31028
20248
20247
20246
8215
20245
20244
20243
20242
20241
20240
20239
20238
20237
20236
20235
20234
20233
8197
20232
20231
20230
20229
20228
20227
20225
20224
20223
20222
20221
20220
20219
20218
20217
20216