©
This document uses PHP Chinese website manual Release
类的变量成员叫做“属性”,或者叫“字段”、“特征”,在本文档统一称为“属性”。属性声明是由关键字 public,protected 或者 private 开头,然后跟一个普通的变量声明来组成。属性中的变量可以初始化,但是初始化的值必须是常数,这里的常数是指 PHP 脚本在编译阶段时就可以得到其值,而不依赖于运行时的信息才能求值。
有关 public,protected 和 private 的更多详细信息,请查看访问控制(可见性)。
Note:
为了向后兼容 PHP 4,PHP 5 声明属性依然可以直接使用关键字 var 来替代(或者附加于)public,protected 或 private。但是已不再需要 var 了。在 PHP 5.0 到 5.1.3,var 会被认为是废弃的,而且抛出
E_STRICT
警告,但是 5.1.3 之后就不再认为是废弃,也不会抛出警告。如果直接使用 var 声明属性,而没有用 public,protected 或 private 之一,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( true , false );
//在 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 新增的。
[#1] nobody [2015-09-17 15:27:51]
class B {
private $ap='B';
static function mb(){
$Z=new A();
echo $Z->ap;
}
}
class A extends B {
public $ap='A';
}
B::mb(); //print 'B',why???????
[#2] anca at techliminal dot com [2015-07-08 23:08:01]
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);
?>
[#3] Anonymous [2014-12-16 09:35:14]
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.
&
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.
[#4] php at webflips dot net [2014-04-08 05:15:13]
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.
[#5] Ashley Dambra [2014-02-16 10:36:02]
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;
}
}
[#6] Ashley Dambra [2014-02-16 10:29:14]
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;
}
}
[#7] AshleyDambra at live dot com [2014-02-16 10:08:22]
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;
}
}
[#8] vpmhieu{at}gmail.com [2013-12-16 10:45:56]
Using heredoc for property declaration is valid (tested), but the 1st example in document list it as invalid declaration.
[#9] singhkumardinesh at gmail dot com [2013-08-23 08:54:04]
if you run this below program it will through the error. but in the example related we have shown that it is possible.
class example {
public $public = self::getStaticFunction();
static function getStaticFunction(){
return 1+1;
}
}
$obj = new example();
echo $obj->public;
ERROR:
( ! ) Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\wamp\www\php\class.php on line 3
[#10] Anonymous [2012-04-17 09:16:40]
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.
[#11] Anonymous [2011-03-11 15:18:28]
$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());
?>
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).
[#12] zzzzBov [2010-06-04 21:21:52]
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.
[#13] Anonymous [2009-11-17 07:51:22]
As of PHP 5.3.0, heredocs can also be used in property declarations.
<?php
class foo {
// As of PHP 5.3.0
public $bar = <<<EOT
bar
EOT;
}
?>