在PHP中向对象添加属性

igo*_*gue 42 php

如何在PHP中向对象添加属性?

Pek*_*ica 66

那么,向对象添加任意属性的一般方法是:

$object->attributename = value;
Run Code Online (Sandbox Code Playgroud)

您可以更清洁,预先定义类中的属性(特定于PHP 5+,在PHP 4中您将使用旧的var $attributename)

class baseclass
 { 

  public $attributename;   // can be set from outside

  private $attributename;  // can be set only from within this specific class

  protected $attributename;  // can be set only from within this class and 
                             // inherited classes
Run Code Online (Sandbox Code Playgroud)

强烈建议这样做,因为您还可以在类定义中记录属性.

您还可以定义在尝试修改对象属性时调用的getter和setter方法.