将属性添加到PHP中的对象 [英] Add attribute to an object in PHP

查看:541
本文介绍了将属性添加到PHP中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you add an attribute to an Object in PHP?

推荐答案

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

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.

这篇关于将属性添加到PHP中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆