downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Klassenkonstanten> <Die Grundlagen
[edit] Last updated: Fri, 17 May 2013

view this page in

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 Eigenschaften, Konstanten und Methoden in der Form $this->Eigenschaft (wobei Eigenschaft der Name der Eigenschaft ist) zugegriffen werden, solange nicht aus dem Kontext einer statischen Methode auf eine statische Eigenschaft zugegriffen wird. In diesem Fall kann mittels self::$Eigenschaft darauf zugegriffen werden. 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.



Klassenkonstanten> <Die Grundlagen
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes Eigenschaften - [4 notes]
up
8
zzzzBov
2 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
5
Anonymous
2 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
5
Anonymous
1 year 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
Anonymous
3 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;
}
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites