PHP 8.3.4 Released!

プロパティ

クラスのメンバ変数のことを プロパティ といいます。 それ以外に フィールド などという呼びかたを見たことがあるかもしれません。 しかし、このマニュアルでは プロパティ と呼ぶことにします。 プロパティは、少なくともひとつのキーワード (たとえば アクセス権 のキーワード、 static キーワード、 PHP 8.1.0 以降のみ readonly) のあとに、 オプションの型宣言 (PHP 7.4 以降、但し readonly を除く) を続け、 その後に通常の変数の宣言を続けます。 宣言時に初期値を設定することもできますが、 初期値は 定数 値でなければなりません。

注意:

クラスのプロパティを宣言する代替の方法として、 var キーワードを使う方法があります。

注意: アクセス権 を宣言しない場合、プロパティを public として宣言したとみなされます。

クラスのメソッドからstatic でないプロパティにアクセスするには -> (オブジェクト演算子) を使って $this->property のようにします (property のところにプロパティ名を指定します)。 staticプロパティへのアクセスには :: (ダブルコロン) を使って self::$property のようにします。 staticプロパティとそうでないプロパティの違いについては、 static キーワード を参照ください。

クラスのメソッドがオブジェクトのコンテキストからコールされたときには、 擬似変数 $this が使えます。 $this は、呼び出し元のオブジェクトの値です。

例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 = [true, false];

public
$var8 = <<<'EOD'
hello world
EOD;
// アクセス権を付けない場合
static $var9;
readonly
int $var10;
}
?>

注意:

クラスやオブジェクトを操作するための便利な関数が用意されています。 クラス/オブジェクト関数 を参照ください。

型宣言

PHP 7.4.0 以降は、プロパティの定義に 型宣言 を含めることができます。 但し、callable 型を除きます。

例2 型付きプロパティの例

<?php

class User
{
public
int $id;
public ?
string $name;

public function
__construct(int $id, ?string $name)
{
$this->id = $id;
$this->name = $name;
}
}

$user = new User(1234, null);

var_dump($user->id);
var_dump($user->name);

?>

上の例の出力は以下となります。

int(1234)
NULL

型付きプロパティは、アクセスする前に初期化しなければいけません。 初期化しないと、Error がスローされます。

例3 プロパティにアクセスする

<?php

class Shape
{
public
int $numberOfSides;
public
string $name;

public function
setNumberOfSides(int $numberOfSides): void
{
$this->numberOfSides = $numberOfSides;
}

public function
setName(string $name): void
{
$this->name = $name;
}

public function
getNumberOfSides(): int
{
return
$this->numberOfSides;
}

public function
getName(): string
{
return
$this->name;
}
}

$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberofSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());

$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>

上の例の出力は以下となります。

string(8) "triangle"
int(3)
string(6) "circle"

Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization

読み取り専用プロパティ

PHP 8.1.0 以降では、readonly を付けてプロパティを宣言できます。 これによって、プロパティを初期化した後に値が変更されることを防止できます。

例4 読み取り専用プロパティの例

<?php

class Test {
public readonly
string $prop;

public function
__construct(string $prop) {
// 正しい初期化
$this->prop = $prop;
}
}

$test = new Test("foobar");
// 正しいプロパティの読み取り
var_dump($test->prop); // string(6) "foobar"

// 不正な再代入です。同じ値を代入することは問題ありません。
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>

注意:

readonly は、 型付きプロパティ に対してのみ指定できます。 型の制約がないプロパティを読み取り専用にしたい場合、 Mixed が使えます。

注意:

読み取り専用の static プロパティはサポートされていません。

読み取り専用プロパティは、一度しか初期化できません。 初期化できるのは、 そのプロパティが宣言された場所と同じスコープに限られます。 これらのルールから外れたプロパティへの代入や変更を行った場合、 Error 例外が発生します。

例5 読み取り専用プロパティの不正な初期化

<?php
class Test1 {
public readonly
string $prop;
}

$test1 = new Test1;
// スコープ外からの不正な初期化
$test1->prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>

注意:

読み取り専用プロパティに対して、 明示的にデフォルト値を設定することはできません。 なぜなら、読み取り専用プロパティにデフォルト値を設定することは、 本質的に定数と同じであり、あまり役に立たないからです。

<?php

class Test {
// Fatal error: Readonly property Test::$prop cannot have default value
public readonly int $prop = 42;
}
?>

注意:

読み取り専用プロパティは、 一度初期化されると unset() できません。 しかし、初期化する前であれば プロパティを宣言した同一のスコープから unset することはできます。

プロパティの変更は、単純な代入にとどまりません。 次に示すプロパティへの変更例は、 すべて Error 例外が発生します:

<?php

class Test {
public function
__construct(
public readonly
int $i = 0,
public readonly array
$ary = [],
) {}
}

$test = new Test;
$test->i += 1;
$test->i++;
++
$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach (
$test as &$prop);
?>

但し、プロパティが読み取り専用であっても、 そのプロパティの内部まで変更できなくなるわけではありません。 読み取り専用プロパティ内部のオブジェクト(またはリソース) は、 内部的に変更しても構いません:

<?php

class Test {
public function
__construct(public readonly object $obj) {}
}

$test = new Test(new stdClass);
// 有効なオブジェクト内部の変更
$test->obj->foo = 1;
// 不正な再代入
$test->obj = new stdClass;
?>

動的なプロパティ

オブジェクトに対して、存在しないプロパティを代入しようとした場合、 PHP は自動的に対応するプロパティを作成します。 こうして作成された動的なプロパティは、 そのインスタンスで のみ 使えます。

警告

動的なプロパティは、PHP 8.2.0 以降は推奨されなくなりました。 代わりに、プロパティを宣言することを推奨します。 任意のプロパティの名前を扱うには、 クラスがマジックメソッド __get()__set() を実装すべきです。 動的なプロパティを使うための最終手段として、 アトリビュート #[\AllowDynamicProperties] でクラスをマークすることができます。

add a note

User Contributed Notes 6 notes

up
342
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
82
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
67
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
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
0
bernard dot dautrevaux at ac6 dot fr
23 days ago
It's not specified above, but, at least in PHP-8, properties declared with the (deprecated but still widely used) keyword 'var' are declared as 'protected', not as 'public' as they used to be before the visibility keywords were introduced.
up
-3
kchlin dot lxy at gmail dot com
1 year ago
From PHP 8.1
It's easy to create DTO object with readonly properties and promoting constructor
which easy to pack into a compact string and covert back to a object.
<?php
# Conversion functions.
# Pack object into a compack JSON string.
function cvtObjectToJson( object $poObject ): string
{
return
json_encode( array_values( get_object_vars( $poObject )));
}

# Unpack object from a JSON string.
function cvtJsonToObject( string $psClass, string $psString ): object
{
return new
$psClass( ...json_decode( $psString ));
}

# DTO example class.
final class exampleDto
{
final public function
__construct(
public readonly
int $piInt,
public readonly ?
int $pnNull,
public readonly
float $pfFloat,
public readonly
string $psString,
public readonly array
$paArray,
public readonly
object $poObject,
){}
}

# Example with export only public properties of given object.
$exampleDtoO = new exampleDto( 1, null, .3, 'string 4', [], new stdClass() );
$stringJson = cvtObjectToJson( $exampleDtoO );// [1,null,0.3,"string 4",[],{}]
$objectO = cvtJsonToObject( exampleDto::class, $stringJson );

# Check and var_dump variables.
echo $exampleDtoO == $objectO
? 'Objects equal, but not identical.'. PHP_EOL
: 'Objects not equal neither identical.'. PHP_EOL
;
var_dump($exampleDtoO, $stringJson, $objectO);

# Output
/*
Objects equal, but not identical
object(exampleDto)#6 (6) {
["piInt"]=>
int(1)
["pnNull"]=>
NULL
["pfFloat"]=>
float(0.3)
["psString"]=>
string(8) "string 4"
["paArray"]=>
array(0) {
}
["poObject"]=>
object(stdClass)#7 (0) {
}
}
string(29) "[1,null,0.3,"string 4",[],{}]"
object(exampleDto)#8 (6) {
["piInt"]=>
int(1)
["pnNull"]=>
NULL
["pfFloat"]=>
float(0.3)
["psString"]=>
string(8) "string 4"
["paArray"]=>
array(0) {
}
["poObject"]=>
object(stdClass)#9 (0) {
}
}
*/
To Top