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, seguido de una declaración normal de variable. Esta declaración puede incluir una inicialización, pero esta inicialización debe ser un valor constante, es decir, debe poder ser evaluada durante la compilación y no depender de información generada durante la ejecución.

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

Nota:

Con el fin de mantener la compatibilidad con PHP 4, PHP 5 continuará aceptando el uso de la palabra reservada var en la declaración de propiedades en lugar de (o además de) public, protected, o private. Sin embargo, var ya no es necesaria. Entre las versiones 5.0 y 5.1.3 de PHP, el uso de var fue considerado obsoleto y emitía una advertencia de nivel E_STRICT; pero a partir de PHP 5.1.3 ya no está obsoleta y no se emite la advertencia.

Si se declara una propiedad utilizando var en lugar de public, protected, o private, PHP tratará dicha propiedad como si hubiera sido definida 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
{
   
// Válido a partir de PHP 5.6.0:
   
public $var1 'hola ' 'mundo';
   
// Válido a partir de PHP 5.3.0:
   
public $var2 = <<<EOD
hola mundo
EOD;
   
// Válido a partir de PHP 5.6.0:
   
public $var3 1+2;
   
// Declaraciones de propiedades inválidas:
   
public $var4 self::miMétodoEstático();
   public 
$var5 $myVar;

   
// Declaraciones de propiedades válidas:
   
public $var6 miConstante;
   public 
$var7 = array(truefalse);

   
// Válido a partir de PHP 5.3.0:
   
public $var8 = <<<'EOD'
hola mundo
EOD;
}
?>

Nota:

Existen varias funciones interesantes para manipular clases y objetos. Puede ser interesante echarle un vistazo a las Funciones de clases/objetos.

A partir de PHP 5.3.0, se puede utilizar heredocs y nowdocs en cualquier contexto de datos estáticos, incluyendo la declaración de propiedades.

Ejemplo #2 Ejemplo del uso de nowdoc para inicializar una propiedad

<?php
class foo {
   
// A paritr de PHP 5.3.0
   
public $bar = <<<'EOT'
bar
EOT;
   public 
$baz = <<<EOT
baz
EOT;
}
?>

Nota:

Se añadio soporte para Nowdoc y Heredoc en PHP 5.3.0.

add a note add a note

User Contributed Notes 9 notes

up
304
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
62
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
52
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
17
php at webflips dot net
10 years ago
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.
up
25
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
-9
Ashley Dambra
10 years ago
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;
    }
}
up
-8
Markus Zeller
7 years ago
Accessing a property without any value initialized will give NULL.

class foo
{
  private $bar;

  public __construct()
  {
      var_dump($this->bar); // null
  }
}
up
-14
AshleyDambra at live dot com
10 years ago
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;
    }
}
up
-27
Anonymous
9 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.

[Editor's note: Removed copy of note by zzzzBov]
To Top