如何在PHP中为对象添加属性?
添加任意属性到对象的一般方式是:
$object->attributename = value;
你可以在类中预定义属性,这样会更加简洁(PHP 5+特有,在PHP 4中你需要使用旧的var $属性名
)
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
这是强烈推荐的,因为你还可以在类定义中记录属性。
您还可以定义getter和setter方法,每当您尝试修改对象的属性时都会调用它们。
这是一个静态类,但实例化后也适用相同原则。此类让您存储和检索所需内容,并在尝试获取未设置内容时抛出错误。
class Settings{
protected static $_values = array();
public static function write( $varName, $val ){
self::$_values[ $varName ] = $val;
}
public static function read( $varName ){
if( !isset( self::$_values[ $varName ] )){
throw new Exception( $varName . ' does not exist in Settings' );
}
return self::$_values[ $varName ];
}
}
请查看php.net文档:http://www.php.net/manual/en/language.oop5.properties.php
在这种情况下,属性被称为“属性”或“类成员”。