Properties

Class member variables are called properties. You may also see them referred to using other terms such as attributes or fields, but for the purposes of this reference we will use properties. They are defined by using one of the keywords public, protected, or private, optionally 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--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Vizibilitatea for more information on the meanings of public, protected, and private.

Notă:

In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.

If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been 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 a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Example #1 property declarations

<?php
class SimpleClass
{
   
// valid as of PHP 5.6.0:
   
public $var1 'hello ' 'world';
   
// valid as of PHP 5.3.0:
   
public $var2 = <<<EOD
hello world
EOD;
   
// valid as of PHP 5.6.0:
   
public $var3 1+2;
   
// invalid property declarations:
   
public $var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// valid property declarations:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// valid as of PHP 5.3.0:
   
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Notă:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Heredoc and Nowdoc

As of PHP 5.3.0 heredocs and nowdocs can be used in any static data context, including property declarations.

Example #2 Example of using a nowdoc to initialize a property

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

Notă:

Nowdoc and Heredoc support was added in PHP 5.3.0.

Type declarations

As of PHP 7.4.0, property definitions can include a type declaration.

Example #3 Example of typed properties

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

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

?>

Exemplul de mai sus va afișa:

int(1234)
NULL

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

Example #4 Accessing properties

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

Exemplul de mai sus va afișa:

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

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

Valid property types

Type Description Minimum PHP version
bool The property must be bool value. PHP 7.4.0
int The property must be an int. PHP 7.4.0
float The property must be a floating point number. PHP 7.4.0
string The property must be a string. PHP 7.4.0
array The property must be an array. PHP 7.4.0
object The property must be an object. PHP 7.4.0
iterable The property must be either an array or an instanceof Traversable. PHP 7.4.0
self The property must be an instanceof the same class in which the property is defined. PHP 7.4.0
parent The property must be an instanceof the parent class of the class in which the property is defined. PHP 7.4.0
Class/interface name The property must be an instanceof the given class or interface name. PHP 7.4.0
?type The property must be the specified type, or null. PHP 7.4.0
add a note add a note

User Contributed Notes 5 notes

up
338
Anonymous
12 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
9 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
65
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
1
kchlin dot lxy at gmail dot com
2 years 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) {
    }
  }
*/
up
26
zzzzBov
14 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.
To Top