且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将属性添加到PHP中的对象

更新时间:2023-12-01 20:23:10

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

Well, the general way to add arbitrary properties to an object is:

$object->attributename = value;

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

You can, much cleaner, pre-define attributes in your class (PHP 5+ specific, in PHP 4 you would use the old 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

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

this is highly recommended, because you can also document the properties in your class definition.

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

You can also define getter and setter methods that get called whenever you try to modify an object's property.