属性

类的变量成员叫做"属性",或者叫"字段"、"特征",在本文档统一称为"属性"。属性声明是由关键字 publicprotected 或者 private 开头,然后跟一个普通的变量声明来组成。属性中的变量可以初始化,但是初始化的值必须是常数,这里的常数是指 PHP 脚本在编译阶段时就可以得到其值,而不依赖于运行时的信息才能求值。

有关 publicprotectedprivate 的更多详细信息,请查看访问控制(可见性)

Note:

为了向后兼容 PHP 4,PHP 5 声明属性依然可以直接使用关键字 var 来替代(或者附加于)publicprotectedprivate。但是已不再需要 var 了。在 PHP 5.0 到 5.1.3,var 会被认为是废弃的,而且抛出 E_STRICT 警告,但是 5.1.3 之后就不再认为是废弃,也不会抛出警告。

如果直接使用 var 声明属性,而没有用 publicprotectedprivate 之一,PHP 5 会将其视为 public

在类的成员方法里面,可以用 ->(对象运算符):$this->property(其中 property 是该属性名)这种方式来访问非静态属性。静态属性则是用 ::(双冒号):self::$property 来访问。更多静态属性与非静态属性的区别参见 Static 关键字

当一个方法在类定义内部被调用时,有一个可用的伪变量 $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 {
   
// 自 5.3.0 起
   
public $bar = <<<'EOT'
bar
EOT;
}
?>

Note:

Nowdoc 支持是在 PHP 5.3.0 新增的。

User Contributed Notes

Markus Zeller 03-Feb-2017 06:53
Accessing a property without any value initialized will give NULL.

class foo
{
  private $bar;

  public __construct()
  {
      var_dump($this->bar); // null
  }
}
anca at techliminal dot com 08-Jul-2015 11:08
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);
?>
Anonymous 16-Dec-2014 09:35
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]
php at webflips dot net 08-Apr-2014 05:15
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.
Ashley Dambra 16-Feb-2014 10:29
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;
    }
}
AshleyDambra at live dot com 16-Feb-2014 10:08
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;
    }
}
Anonymous 17-Apr-2012 09:16
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.
Anonymous 11-Mar-2011 03:18
$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).
zzzzBov 04-Jun-2010 09:21
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.