PHP 8.3.4 Released!

Propiedades

Las variables pertenecientes a una clase se llaman propiedades. También se les puede llamar usando otros términos como atributos, o campos, pero para los propósitos de esta referencia se va a utilizar propiedades. Éstas se definen usando una de las palabras reservadas public, protected, o private, opcionalmente, a partir de PHP 7.4, seguido de una declaración de tipo, seguida de una declaración de variable normal. Esta declaración puede incluir una inicialización, pero esta inicialización debe ser un valor de constante.

Véase la Visibilidad para más información sobre el significado de public, protected, y private.

Nota:

Como alternativa y no recomendada de declarar las propiedades de una clase, ya que es para mantener la compatibilidad con PHP 4, se acepta el uso de la palabra reservada var. Esta tratará la propiedad de forma idéntica a como se hubiera declarado como public.

Dentro de los métodos de una clase, se puede acceder a las propiedades no estáticas utilizando -> (el operador de objeto): $this->propiedad (donde propiedad es el nombre de la propiedad). A las propiedades estáticas se puede acceder utilizando :: (doble dos puntos): self::$propiedad. Véase la palabra reservada 'static' para más información sobre la diferencia entre propiedades estáticas y no estáticas.

La pseudovariable $this está disponible dentro de cualquier método de clase cuando éste es invocado dentro del contexto de un objeto. $this es una referencia al objeto invocador (usualmente el objeto al cual pertenece el método, aunque puede que sea otro objeto si el método es llamado estáticamente desde el contexto de un objeto secundario).

Ejemplo #1 Declaración de propiedades

<?php
class ClaseSencilla
{
public
$var1 = 'hola ' . 'mundo';
public
$var2 = <<<EOD
hola mundo
EOD;
public
$var3 = 1+2;
// Declaraciones de propiedades inválidas:
public $var4 = self::miMetodoEstatico();
public
$var5 = $myVar;

// Declaraciones de propiedades válidas:
public $var6 = miConstante;
public
$var7 = [true, false];

public
$var8 = <<<'EOD'
hola mundo
EOD;
}
?>

Nota:

Existen varias funciones para manipular clases y objetos. Véase Las funciones de clases/objetos.

Declaraciones de tipo

A partir de PHP 7.4.0, las definiciones de propiedades pueden incluirse Declaraciones de tipo, con la excepción de los callable.

Ejemplo #2 Ejemplo de propiedades tipadas

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

?>

El resultado del ejemplo sería:

int(1234)
NULL

Las propiedades tipadas deben ser inicializadas antes de acceder a ellas, de lo contrario se produce un Error.

Ejemplo #3 Acceso a las propiedades

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

El resultado del ejemplo sería:

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

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

Propiedad Readonly

A partir de PHP 8.1.0, una propiedad se puede declarar con el modificador readonly (de solo lectura), lo que impide la modificación de la propiedad después de la inicialización.

Ejemplo #4 Ejemplo de propiedades de solo lectura

<?php

class Test {
public readonly
string $prop;

public function
__construct(string $prop) {
// Inicialización.
$this->prop = $prop;
}
}

$test = new Test("foobar");
// Lectura.
var_dump($test->prop); // string(6) "foobar"

// Reasignación ilegal. No importa que el valor asignado sea el mismo.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>

Nota:

El modificador readonly solo se puede aplicar a las propiedades tipadas. Se puede crear una propiedad readonly sin restricciones mediante el tipo mixed.

Nota:

El modificador readonly no son compatibles en propiedades estáticas.

Una propiedad readonly solo se puede inicializar una vez, y solo desde el ámbito en el que se ha declarado. Cualquier otra asignación o modificación de la propiedad dará lugar a una excepción de Error.

Ejemplo #5 Inicialización ilegal de propiedades readonly

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

$test1 = new Test1;
// Inicialización ilegal fuera del ámbito privado.
$test1->prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>

Nota:

No se permite especificar un valor predeterminado explícito en las propiedades readonly, porque una propiedad readonly con un valor predeterminado es esencialmente la misma que una constante y, por lo tanto, no es particularmente útil.

<?php

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

Nota:

Las propiedades readonly no pueden usarse con la función unset() una vez inicializadas. Sin embargo, es posible desactivar una propiedad readonly antes de la inicialización, desde el ámbito donde se ha declarado la propiedad.

Las modificaciones no son necesariamente asignaciones simples, todo lo siguiente también dará lugar a una excepción 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);
?>

Sin embargo, las propiedades readonly no excluyen la mutabilidad interior. Los objetos (o recursos) almacenados en propiedades readonly aún pueden modificarse internamente:

<?php

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

$test = new Test(new stdClass);
// Mutación interior.
$test->obj->foo = 1;
// Reasignación ilegal.
$test->obj = new stdClass;
?>

Dynamic properties

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

Advertencia

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.

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