Php objects and properties

Php objects and properties

Class member variables are called properties. They may be referred to using other terms such as fields, but for the purposes of this reference properties will be used. They are defined by using at least one modifier (such as Visibility, Static Keyword, or, as of PHP 8.1.0, readonly), optionally (except for readonly properties), as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value.

Note:

An obsolete way of declaring class properties, is by using the var keyword instead of a modifier.

Note: A property declared without a Visibility modifier will be declared as public .

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property . See Static Keyword for more information on the difference between static and non-static properties.

The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is the value of the calling object.

Example #1 Property declarations

class SimpleClass
public $var1 = ‘hello ‘ . ‘world’ ;
public $var2 = hello world
EOD;
public $var3 = 1 + 2 ;
// invalid property declarations:
public $var4 = self :: myStaticMethod ();
public $var5 = $myVar ;

// valid property declarations:
public $var6 = myConstant ;
public $var7 = [ true , false ];

public $var8 = hello world
EOD;

// Without visibility modifier:
static $var9 ;
readonly int $var10 ;
>
?>

Note:

There are various functions to handle classes and objects. See the Class/Object Functions reference.

Type declarations

As of PHP 7.4.0, property definitions can include Type declarations, with the exception of callable .

Example #2 Example of typed properties

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 );

The above example will output:

Typed properties must be initialized before accessing, otherwise an Error is thrown.

Example #3 Accessing properties

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 ());
?>

The above example will output:

string(8) "triangle" int(3) string(6) "circle" Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization

Readonly properties

As of PHP 8.1.0, a property can be declared with the readonly modifier, which prevents modification of the property after initialization.

Example #4 Example of readonly properties

class Test public readonly string $prop ;

public function __construct ( string $prop ) // Legal initialization.
$this -> prop = $prop ;
>
>

$test = new Test ( «foobar» );
// Legal read.
var_dump ( $test -> prop ); // string(6) «foobar»

// Illegal reassignment. It does not matter that the assigned value is the same.
$test -> prop = «foobar» ;
// Error: Cannot modify readonly property Test::$prop
?>

Note:

The readonly modifier can only be applied to typed properties. A readonly property without type constraints can be created using the Mixed type.

Note:

Readonly static properties are not supported.

A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an Error exception.

Example #5 Illegal initialization of readonly properties

class Test1 public readonly string $prop ;
>

$test1 = new Test1 ;
// Illegal initialization outside of private scope.
$test1 -> prop = «foobar» ;
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>

Note:

Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful.

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

Note:

Readonly properties cannot be unset() once they are initialized. However, it is possible to unset a readonly property prior to initialization, from the scope where the property has been declared.

Modifications are not necessarily plain assignments, all of the following will also result in an Error exception:

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 );
?>

However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally:

class Test public function __construct (public readonly object $obj ) <>
>

$test = new Test (new stdClass );
// Legal interior mutation.
$test -> obj -> foo = 1 ;
// Illegal reassignment.
$test -> obj = new stdClass ;
?>

Dynamic properties

If trying to assign to a non-existent property on an object , PHP will automatically create a corresponding property. This dynamically created property will only be available on this class instance.

Dynamic properties are deprecated as of PHP 8.2.0. It is recommended to declare the property instead. To handle arbitrary property names, the class should implement the magic methods __get() and __set(). At last resort the class can be marked with the #[\AllowDynamicProperties] attribute.

User Contributed Notes 5 notes

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;

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;

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.

You can access property names with dashes in them (for example, because you converted an XML file to an object) in the following way:

$ref = new StdClass ();
$ref -> < 'ref-type' >= ‘Journal Article’ ;
var_dump ( $ref );
?>

$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.

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 ());

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

*/
?>

This is documented behavior when converting any object to an array (see 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: PHP manual page).

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.

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.

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.
# 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) >
>
*/

Оцените статью