Свойства

Переменные, которые являются членами класса, называются "свойства". Также их называют, используя другие термины, такие как "аттрибуты" или "поля", но в рамках этой документации, мы будем называть их свойствами. Они определяются с помощью ключевых слов public, protected, или private, следуя правилам правильного описания переменных. Это описание может содержать инициализацию, но инициализация дожна применяться для константных значений - то есть, переменные должны быть вычислены во время компиляции и не должны зависеть от информации программы во время выполнения для их вычисления.

Смотри Область видимости для получения информации о применении public, protected, и private.

Замечание:

Для того, чтобы поддерживать обратную совместимость с PHP 4, PHP 5 по-прежнему позволяет использовать ключевое слово var при определении свойств вместо (или в дополнении к) public, protected, или private. Однако, var больше не требуется. В версиях PHP с 5.0 по 5.1.3, использование var считалось устаревшим вызывало E_STRICT предупреждение, но с PHP 5.1.3 больше не считается устаревшим и не выдает предупреждения.

Если, для определения свойства, вы используете var вместо одного из: public, protected, или private, тогда PHP 5 будет определять свойство как public.

В пределах методов класса доступ к нестатическим свойствам может быть получен с помощью -> (объектного оператора): $this->property (где property - имя свойства). Доступ к статическим свойствам может быть получен с помощью :: (двойного двоеточия): self::$property. Подробнее о различиях между статическими и нестатическими свойствами смотрите в разделе "Ключевое слово Static" для получения большей информации.

Псевдо-переменная $this доступна внутри любого метода класса, когда этот метод вызывается в пределах объекта. $this - это ссылка на вызываемый объект (обычно, объект, которому принадлежит метод, но возможно и другого объекта, если метод вызван статически из контекста второго объекта).

Пример #1 Определение свойств

<?php
class SimpleClass
{
   
// неправильное определение свойств:
   
public $var1 'hello ' 'world';
   public 
$var2 = <<<EOD
hello world
EOD;
   public 
$var3 1+2;
   public 
$var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// правильное определение свойств:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// Это разрешено только в PHP 5.3.0 и более поздних версиях.
   
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Замечание:

Существуют несколько интересных функций для обработки классов и объектов. Вы можете их увидеть тут Class/Object Functions.

В отличии от heredocs, nowdocs может быть использованы в любом статическом контексте данных, включая определение свойств.

Пример #2 Пример использования nowdoc для инициализации свойств

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

Замечание:

Поддержка nowdoc была добавлена в PHP 5.3.0.

Коментарии

Автор:
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.
2010-06-05 00:21:52
http://php5.kiev.ua/manual/ru/language.oop5.properties.html
Автор:
$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).
2011-03-11 17:18:28
http://php5.kiev.ua/manual/ru/language.oop5.properties.html
Автор:
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.
2012-04-17 12:16:40
http://php5.kiev.ua/manual/ru/language.oop5.properties.html
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);
?>
2015-07-09 02:08:01
http://php5.kiev.ua/manual/ru/language.oop5.properties.html
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 cvtObjectToJsonobject $poObject ): string
{
  return 
json_encodearray_valuesget_object_vars$poObject )));
}

# Unpack object from a JSON string.
function cvtJsonToObjectstring $psClassstring $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 exampleDto1null.3'string 4', [], new stdClass() );
$stringJson  cvtObjectToJson$exampleDtoO );// [1,null,0.3,"string 4",[],{}]
$objectO     cvtJsonToObjectexampleDto::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) {
    }
  }
*/
2022-09-20 18:39:31
http://php5.kiev.ua/manual/ru/language.oop5.properties.html
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.
2024-02-24 19:25:08
http://php5.kiev.ua/manual/ru/language.oop5.properties.html

    Поддержать сайт на родительском проекте КГБ