php

Class

hojomu 2023. 9. 6. 09:07

php에서 클래스(객체)를 생성하고 선언하는 방법을 알아보자

 

class Account{
    public int $number;
    public string $type;
    public float $balance;
    
    public function __construct($number, $type, $balance)
    {
    	$this->number = $number;
    	$this->type = $type;
    	$this->balance = $balance;
    }
    
    public function deposit(float $amount): float
    {
    }
    
    public function withdraw(float $amount): float
    {
    }
}

 

1. 객체 인스턴스

$account = new Account;

$account2 = nes Account(123456 , 'checking' , 15555.00);

-> 기본적으로 첫 번째 방법으로 인스턴스를 생성한다. 

두 번째 방법은 __construct 가 선언되어있을 때 이용할 수 있다. 

public function __construct(
	public int $number,
    public string $type,
    public float $balance = 0.00,
) {}

이런 방법으로도 선언할 수 있다.  $balance는 옵셔널로 선언된 것이다.

 

2. 속성에 접근하기

인스턴스가 생성되었다면, 필드나 메서드에 접근할 수 있다

$account -> balance = 555.33;

$account -> deposit( 3255.33 );

인스턴스가 생성된 변수에서 다음과 같이 필드에 접근하거나 메서드를 활용할 수 있다.

 

3. 이 객체의 속성에 접근하기

class Account{
public float $balance;

public function deposit($amount){
$this->balance += $amount;
return $this->balance;
}
}

클래스(객체)에서 객체 자신이 가지고 있는 요소에 접근하려면 $this (의사변수 pseudo-variable)을 활용하자

 

4. Getter / Setter

protected 속성에 저장된 데이터는 외부에서 접근할 수 없다.

이런 경우 Getter / Setter를 만들어서 해당 속성에 접근할 수 있다.

 

5. 객체 속에 객체를 저장

객체의 필드에 다른 객체를 저장하고싶으면, array 타입으로 지정한다.

class Customer
{
  public string $forename;
  public string $surname;
  public string $email;
  private string $password;
  public array $accounts;
  
  function __construct(string $forename, string $surname, string $email, string $password, array $accounts)
  {
    ...
    
    $this-> accounts = $account;
  }
  
  function getFullName()
  {
    return $this->forename . ' ' . $this->surname;
  }
  
}