PHP 5.4.36 Released

Eigenschaften

Variablen in einer Klasse werden "Eigenschaften" genannt. Die Begriffe "Attribute" oder "Felder" werden ebenfalls verwendet, um sich auf das selbe Konzept zu beziehen, aber innerhalb dieser Referenz wird der Begriff "Eigenschaften" verwendet. Diese werden definiert, indem man eines der Schlüsselwörter public, protected oder private gefolgt von einer regulären Variablendeklaration verwendet. Die Deklaration darf eine Initialisierung des Variablenwertes beinhalten, der zu setzende Wert muss dabei allerdings ein konstanter Wert sein - d.h. dieser muss zum Kompilierungszeitpunkt ausgewertet werden können und darf nicht von Informationen abhängen, die erst zur Laufzeit zur Verfügung stehen.

Siehe Sichtbarkeit für mehr Informationen zur Bedeutung von public, protected und private.

Hinweis:

Um Abwärtskompatibilität mit PHP 4 zu gewährleisten, akzeptiert PHP 5 weiterhin die Verwendung des Schlüsselwortes var zur Deklaration von Eigenschaften anstelle von (oder zusätzlich zu) public, protected oder private. var wird jedoch nicht mehr benötigt. In den Versionen von PHP 5.0 bis 5.1.3 wurde die Verwendung von var als veraltet betrachtet und erzeugte eine E_STRICT-Warnung, aber seit PHP 5.1.3 ist dies nicht länger veraltet und erzeugt keine Warnung.

Wenn eine Eigenschaft mittels var anstelle von public, protected oder private deklariert wird, so wird PHP 5 diese Eigenschaft so behandeln, als wäre sie mittels public deklariert worden.

Innerhalb der Methoden einer Klasse kann auf nicht-statische Eigenschaften zugegriffen werden, indem man (den Objektoperator) -> verwendet: $this-$gt;Eigenschaft(wobei Eigenschaft der Name der Eigenschaft ist). Zugriff auf statische Eigenschaften erhält man, indem man (den Doppel-Doppelpunkt) :: verwendet: self::$Eigenschaft. Siehe auch Static-Schlüsselwort für mehr Informationen zu diesem Thema.

Die Pseudo-Variable $this ist innerhalb jeder Klassenmethode verfügbar, wenn diese Methode im Kontext eines Objektes aufgerufen wird. $this ist eine Referenz auf das aufrufende Objekt (üblicherweise das Objekt, zu dem diese Methode gehört; möglicherweise ein anderes Objekt, wenn die Methode statisch aus einem sekundären Objekt aufgerufen wird).

Beispiel #1 Deklaration von Eigenschaften

<?php
class SimpleClass
{
   
// Ungültige Deklarationen von Eigenschaften:
   
public $var1 'Hallo ' 'Welt';
   public 
$var2 = <<<EOD
Hallo Welt
EOD;
   public 
$var3 1+2;
   public 
$var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// Gültige Deklarationen von Eigenschaften:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// Dies ist nur in PHP 5.3.0 oder später gültig.
   
public $var8 = <<<'EOD'
Hallo Welt
EOD;
}
?>

Hinweis:

Es gibt einige nützliche Funktionen für den Umgang mit Klassen und Objekten. Siehe hierzu Klassen- und Objekt-Funktionen.

Im Gegensatz zur Heredoc-Syntax kann die Nowdoc-Syntax in jedem Kontext für statische Daten verwendet werden, einschließlich der Deklaration von Eigenschaften.

Beispiel #2 Beispiel für ein nowdoc zur Initialisierung einer Eigenschaft

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

Hinweis:

Unterstützung für Nowdoc wurde in PHP 5.3.0 hinzugefügt.

add a note add a note

User Contributed Notes 11 notes

up
80
Anonymous
2 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
4
php at webflips dot net
8 months 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
29
Anonymous
3 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
19
zzzzBov
4 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
8
Ashley Dambra
10 months 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
0
Anonymous
4 days 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.
                                                               &
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
-2
AshleyDambra at live dot com
10 months 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
-5
vpmhieu{at}gmail.com
1 year ago
Using heredoc for property declaration is valid (tested), but the 1st example in document list it as invalid declaration.
up
-9
singhkumardinesh at gmail dot com
1 year ago
if you run this below program it will through the error. but in the example related we have shown that it is possible.

class example {
    public $public = self::getStaticFunction();
    static function getStaticFunction(){
        return 1+1;
    }
}
$obj = new example();
echo $obj->public;

ERROR:

( ! ) Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\wamp\www\php\class.php on line 3
up
-16
Anonymous
5 years ago
As of PHP 5.3.0, heredocs can also be used in property declarations.

<?php
class foo {
  
// As of PHP 5.3.0
  
public $bar = <<<EOT
bar
EOT;
}
?>
up
-5
Ashley Dambra
10 months 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;
    }
}
To Top