프로퍼티

클래스 멤버 변수들을 "프로퍼티(properties)" 라고 부릅니다. "애튜리뷰트(attributes)" 나 "필드(fields)" 라는 이름으로 불렀을지 모르지만, 이 문서에서는 "프로퍼티"를 사용하도록 하겠습니다. 프로퍼티는 public, protected, 또는 private 키워드를 붙일수 있으며, 이어 일반적인 변수선언이 뒤따릅니다. 선언시에 변수를 초기화 할수 있지만 반드시 상수여야 합니다.-- 이것은, 컴파일 타임에 평가 가능한 값이어야 함을 의미합니다.

public, protected, 와 private 의 의미에 대한 정보는 가시성 를 참고 하시기 바랍니다..

Note:

PHP 4 와의 하위 호환성을 유지하기 위해, PHP 5 는 아직도 프로퍼티를 선언할때 public, protected, 또는 private 키워드를 사용하는 방법과 함께 var 키워드를 사용하는것을 허용하고 있습니다. 그렇긴 하지만, var 키워드는 더이상 필수가 아니므로 사용에 제한을 둘것을 권장합니다. PHP 5.0 에서 5.1.3 까지는 var 키워드는 비추천 으로 간주되어 E_STRICT 경고를 발생했습니다. 하지만, PHP 5.1.3 이후로는 더이상 비추천이 아니며, 경고도 발생하지 않습니다.

public, protected, 또는 private 중의 하나 대신에 var 키워드로 프로퍼티를 선언했다면, PHP 5 는 public 으로 선언한것으로 다루게 됩니다.

클래스 메서드 내에서 비정적 프로퍼티는 -> (객체 연산자) 를 사용하여 접근 가능합니다: $this->property (여기서 property 는 프로퍼티명을 의미함). 정적 프로퍼티들은 :: (Double Colon) 을 사용하여 접근 가능합니다:self::$property. 정적, 비정적 프로퍼티의 차이점을 알고 싶을 경우 스태틱 키워드 를 참고 하시기 바랍니다.

의사-변수 $this 는 객체 내부에서 메서드가 호출되었을때 어떤 클래스의 내부에서든지 존재하는 값입니다. $this 는 현재 호출한 객체를 참조합니다.(보통은 메서드가 속한 객체를 참조하지만, 만약에 메서드가 다른객체로부터 정적으로 호출되었다면 다른 객체를 참조하는것도 가능합니다.)

Example #1 프로퍼티 선언

<?php
class SimpleClass
{
   
// 잘못된 프로퍼티 선언:
   
public $var1 'hello ' 'world';
   public 
$var2 = <<<EOD
hello world
EOD;
   public 
$var3 1+2;
   public 
$var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// 유효한 프로퍼티 선언:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// PHP 5.3.0 이후부터 가능합니다.
   
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Note:

클래스와 객체를 다루는 몇가지 좋은 함수들이 존재 합니다. 원한다면 참고 하시기 바랍니다. 클래스/객체 함수들.

heredocs 과는 다르게, nowdocs 은 어떤 정적 데이터 컨텍스트이든지 사용할 수 있으며, 프로퍼티도 그중하나 입니다.

Example #2 nowdoc을 이용한 프로퍼티 초기화 예제

<?php
class foo {
   
// As of PHP 5.3.0
   
public $bar = <<<'EOT'
bar
EOT;
}
?>

Note:

PHP 5.3.0 이후부터 nowdoc지원이 추가 되었습니다.

add a note add a note

User Contributed Notes 9 notes

up
323
Anonymous
11 years ago
In case this saves anyone any time, I spent ages working out why the following didn't work:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->$foo = TRUE;

        echo($this->$foo);
    }
}

$bar = new MyClass();

giving "Fatal error: Cannot access empty property in ...test_class.php on line 8"

The subtle change of removing the $ before accesses of $foo fixes this:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->foo = TRUE;

        echo($this->foo);
    }
}

$bar = new MyClass();

I guess because it's treating $foo like a variable in the first example, so trying to call $this->FALSE (or something along those lines) which makes no sense. It's obvious once you've realised, but there aren't any examples of accessing on this page that show that.
up
65
anca at techliminal dot com
8 years ago
You can access property names with dashes in them (for example, because you converted an XML file to an object) in the following way:

<?php
$ref
= new StdClass();
$ref->{'ref-type'} = 'Journal Article';
var_dump($ref);
?>
up
58
Anonymous
13 years ago
$this can be cast to array.  But when doing so, it prefixes the property names/new array keys with certain data depending on the property classification.  Public property names are not changed.  Protected properties are prefixed with a space-padded '*'.  Private properties are prefixed with the space-padded class name...

<?php

class test
{
    public
$var1 = 1;
    protected
$var2 = 2;
    private
$var3 = 3;
    static
$var4 = 4;
   
    public function
toArray()
    {
        return (array)
$this;
    }
}

$t = new test;
print_r($t->toArray());

/* outputs:

Array
(
    [var1] => 1
    [ * var2] => 2
    [ test var3] => 3
)

*/
?>

This is documented behavior when converting any object to an array (see </language.types.array.php#language.types.array.casting> PHP manual page).  All properties regardless of visibility will be shown when casting an object to array (with exceptions of a few built-in objects).

To get an array with all property names unaltered, use the 'get_object_vars($this)' function in any method within class scope to retrieve an array of all properties regardless of external visibility, or 'get_object_vars($object)' outside class scope to retrieve an array of only public properties (see: </function.get-object-vars.php> PHP manual page).
up
16
php at webflips dot net
9 years ago
Heredoc IS valid as of PHP 5.3 and this is documented in the manual at http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Only heredocs containing variables are invalid because then it becomes dynamic.
up
28
zzzzBov
13 years ago
Do not confuse php's version of properties with properties in other languages (C++ for example).  In php, properties are the same as attributes, simple variables without functionality.  They should be called attributes, not properties.

Properties have implicit accessor and mutator functionality.  I've created an abstract class that allows implicit property functionality.

<?php

abstract class PropertyObject
{
  public function
__get($name)
  {
    if (
method_exists($this, ($method = 'get_'.$name)))
    {
      return
$this->$method();
    }
    else return;
  }
 
  public function
__isset($name)
  {
    if (
method_exists($this, ($method = 'isset_'.$name)))
    {
      return
$this->$method();
    }
    else return;
  }
 
  public function
__set($name, $value)
  {
    if (
method_exists($this, ($method = 'set_'.$name)))
    {
     
$this->$method($value);
    }
  }
 
  public function
__unset($name)
  {
    if (
method_exists($this, ($method = 'unset_'.$name)))
    {
     
$this->$method();
    }
  }
}

?>

after extending this class, you can create accessors and mutators that will be called automagically, using php's magic methods, when the corresponding property is accessed.
up
-14
Ashley Dambra
10 years ago
Updated method objectThis() to transtypage class array properties or array to stdClass.

Hope it help you.

public function objectThis($array = null) {
    if (!$array) {
        foreach ($this as $property_name => $property_values) {
            if (is_array($property_values) && !empty($property_values)) {
                $this->{$property_name} = $this->objectThis($property_values);
            } else if (is_array($property_values) && empty($property_values)) {
                $this->{$property_name} = new stdClass();
            }
        }
    } else {
        $object = new stdClass();
        foreach ($array as $index => $values) {
            if (is_array($values) && empty($values)) {
                $object->{$index} = new stdClass();
            } else if (is_array($values)) {
                $object->{$index} = $this->objectThis($values);
            } else {
                $object->{$index} = $values;
            }
        }
        return $object;
    }
}
up
-8
Markus Zeller
7 years ago
Accessing a property without any value initialized will give NULL.

class foo
{
  private $bar;

  public __construct()
  {
      var_dump($this->bar); // null
  }
}
up
-18
AshleyDambra at live dot com
10 years ago
Add this method to you class in order to 'transtypage' all the array properties into stdClass();

Hope it help you.

public function objectThis($object = null) {
    if (!$object) {
        foreach ($this as $property_name => $property_values) {
            if (is_array($property_values)) {
                $this->{$property_name} = $this->objectThis($property_values);
            }
        }
    } else {
        $object2 = new stdClass();
        foreach ($object as $index => $values) {
            if (is_array($values)) {
                $object2->{$index} = $this->objectThis($values);
            } else {
                $object2->{$index} = $values;
            }
        }
        return $object2;
    }
}
up
-31
Anonymous
9 years ago
In case this saves anyone any time, I spent ages working out why the following didn't work:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->$foo = TRUE;

        echo($this->$foo);
    }
}

$bar = new MyClass();

giving "Fatal error: Cannot access empty property in ...test_class.php on line 8"

The subtle change of removing the $ before accesses of $foo fixes this:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->foo = TRUE;

        echo($this->foo);
    }
}

$bar = new MyClass();

I guess because it's treating $foo like a variable in the first example, so trying to call $this->FALSE (or something along those lines) which makes no sense. It's obvious once you've realised, but there aren't any examples of accessing on this page that show that.

[Editor's note: Removed copy of note by zzzzBov]
To Top