개발블로그

PHP 변수 대입과 객체 복제 본문

STUDY/PHP

PHP 변수 대입과 객체 복제

devmel 2026. 9. 5. 19:40
Contents 접기
 

기본값 대입

 

개념

대입 연산자(=) = 오른쪽 값을 왼쪽 변수에 저장하는 연산자

=> 숫자나 문자열을 다른 변수에 대입하면, 각 변수의 값은 독립적으로 사용할 수 있음. 

이후 한 변수의 값을 변경해도 다른 변수에는 영향을 주지 않음

$variableA = 값;
$variableB = $variableA;

// $variableB에는 대입 시점의 $variableA 값이 전달된다. 이후 $variableA의 변경을 자동으로 따라가지는 않는다.

 

ex)

// 숫자 대입
$number = 10;
$otherNumber = $number;

$otherNumber = 20;

echo $number;      // 10
echo $otherNumber; // 20


// 문자열 대입
$name = "Kim";
$otherName = $name;

$name = "Lee";

echo $name;      // Lee
echo $otherName; // Kim

 

 

 


 

객체 대입

 

개념

객체를 다른 변수에 대입하면, 객체가 복제되는 대신 두 변수가 같은 객체를 가리킴

=> PHP의 객체 변수에는 특정 객체에 접근하는 객체 식별자가 담긴다. = 로 대입하면 이 식별자가 복사됨

=> 같은 객체를 가리키므로 한 변수를 통해 속성을 변경하면 다른 변수에서도 변경된 값을 확인할 수 있음

 

$objectA = new ClassName();
$objectB = $objectA;

/*
$objectA ──┐
           ├──→ 하나의 객체
$objectB ──┘

=>변수는 두 개지만, 객체는 하나
*/

 

ex)

class UserProfile
{
    public string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

$user = new UserProfile("Kim");
$other = $user;

$other->name = "Lee";
/*
$other->name = "Lee"
→ 두 변수가 가리키는 객체의 name 변경

$user  ──┐
         ├──→ UserProfile
$other ──┘      name: "Lee"
*/

echo $user->name;  // Lee
echo $other->name; // Lee

 

객체 재대입

한 변수에 새로운 객체를 대입하면 그 변수가 가리키는 대상만 바뀜

ex)

$user = new UserProfile("Kim");
$other = $user;

$other = new UserProfile("Lee");

echo $user->name;  // Kim
echo $other->name; // Lee

/*
$user  ───→ 기존 객체
              name: "Kim"

$other ───→ 새로운 객체
              name: "Lee"
*/

 

 


 

참조 대입

 

개념

두 변수 이름이 같은 변수 내용을 공유하도록 연결하는 방식 

- 연결된 이후에는 어느 쪽에 값을 대입하든 다른 변수에서도 변경된 값이 나타남

 

문법

$variableA = 값;
$variableB =& $variableA;
/*
$variableA ──┐
             ├──→ 공유하는 값
$variableB ──┘

=> $variableB를 $variableA의 또 다른 이름처럼 사용할 수 있다.
*/

 

예시

/*
기본값의 참조 대입
*/
$number = 10;
$otherNumber =& $number;

$otherNumber = 20;

echo $number;      // 20
echo $otherNumber; // 20

$number = 30;

echo $number;      // 30
echo $otherNumber; // 30


/*
객체의 참조 대입
=> 객체 속성 변경뿐 아니라 새로운 객체를 대입한 결과도 공유함
*/
$user = new UserProfile("Kim");
$other =& $user;

$other = new UserProfile("Lee");

echo $user->name;  // Lee
echo $other->name; // Lee

 

 

주의점

객체 공유와 참조 재입의 구분

객체를 함께 수정하기 위해 반드시 &가 필요한 것은 아님

=> 일반 대입만으로도 같은 객체를 가리키므로 속성 변경을 함께 확인할 수 있다. 

참조 대입은 변수에 다른 값을 재대입한 결과까지 공유해야 하는지 따져보고 사용함.

 

 


 

객체 복제

개념

기존 객체의 속성값을 바탕으로 새로운 객체를 만드는 동작.

일반 대입(=)은 같은 객체를 가리키지만, clone은 별도의 객체를 생성함

 

문법

$original = new ClassName();
$copy = clone $original;

/*
$original ───→ 원본 객체
$copy     ───→ 복제된 객체
=> 복제 직후에는 속성값이 같더라도 서로 다른 객체
*/

 

 

예시

ex)

$user = new UserProfile("Kim");
$copy = clone $user;

$copy->name = "Lee";

echo $user->name; // Kim
echo $copy->name; // Lee

/* 
[실행과정]
① 원본 생성

$user ───→ UserProfile
             name: "Kim"

② 복제

$user ───→ UserProfile
             name: "Kim"

$copy ───→ UserProfile
             name: "Kim"

③ 복제본의 이름 변경

$user ───→ UserProfile
             name: "Kim"

$copy ───→ UserProfile
             name: "Lee"
*/

 

 

 


 

얕은 복사와 깊은 복사

 

개념

객체의 속성에는 문자열이나 숫자뿐 아니라 다른 객체도 들어갈 수 있다. 

이때 복제 범위에 따라 얕은 복사와 깊은 복사를 구분함.

구분 복제 범위 내부 객체
얕은 복사 바깥 객체를 복제 원본과 복제본이 공유
깊은 복사 내부 객체까지 복제 원본과 복제본이 별도로 사용

 

 

예시

/**
[얕은 복사]
*/
class Address
{
    public string $city = "Seoul";
}

class UserProfile
{
    public string $name = "Kim";
    public Address $address;

    public function __construct()
    {
        $this->address = new Address();
    }
}

$user = new UserProfile();
$copy = clone $user;
/*
$user → 원본 UserProfile
          address ──┐
                    ├──→ 하나의 Address
$copy → 복제 UserProfile   city: "Seoul"
          address ──┘
*/

// 복제본의 이름과 주소를 변경해 보기
$copy->name = "Lee";
$copy->address->city = "Busan";

echo $user->name;          // Kim
echo $copy->name;          // Lee

echo $user->address->city; // Busan
echo $copy->address->city; // Busan


/**
[깊은 복사]

주소까지 독립적으로 변경하려면 내부의 Address도 별도로 복제해야 함
=> 별도의 deep clone 연산자가 없기 때문에, 필요한 내부 객체를 직접 복제해야 함
*/

 

 

깊은 복사 방법 

__clone() 안에서 내부 객체를 추가로 복제하면, 원본과 복제본이 서로 다른 내부 객체를 사용하도록 만들 수 있음.

 

public function __clone(): void
{
    $this->property = clone $this->property;
}

 

EX]

class Address
{
    public string $city = "Seoul";
}

class UserProfile
{
    public string $name = "Kim";
    public Address $address;

    public function __construct()
    {
        $this->address = new Address();
    }

    public function __clone(): void
    {
        $this->address = clone $this->address;
    }
}

$user = new UserProfile();
$copy = clone $user;

$copy->address->city = "Busan";

echo $user->address->city; // Seoul
echo $copy->address->city; // Busan

 

 

주의점

복제 범위 설정

내부 객체를 무조건 모두 복제하기보다, 복제본에서 독립적으로 변경해야 하는 데이터인지 먼저 판단

 

 

'STUDY > PHP' 카테고리의 다른 글

[객체지향] PHP final 키워드  (0) 2026.09.05
[객체지향] PHP Trait  (1) 2026.09.05
[객체지향] PHP 매직 메서드  (0) 2026.09.05
[객체지향] PHP static과 스코프 해석 연산자  (0) 2026.09.05
PHP 네임스페이스와 use  (0) 2026.09.05