在 PHP 中为对象添加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2850844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:53:43  来源:igfitidea点击:

Add attribute to an object in PHP

php

提问by igorgue

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

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

回答by Pekka

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

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

$object->attributename = value;

You can, much cleaner, pre-define attributes in your class (PHP 5+ specific, in PHP 4 you would use the old var $attributename)

您可以更清晰地在类中预定义属性(特定于 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

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

这是强烈推荐的,因为您还可以在类定义中记录属性。

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

您还可以定义getter 和 setter 方法,每当您尝试修改对象的属性时,它们都会被调用。

回答by jordanstephens

Take a look at the php.net documentation: http://www.php.net/manual/en/language.oop5.properties.php

看看 php.net 文档:http://www.php.net/manual/en/language.oop5.properties.php

Attributes are referred to as "properties" or "class members" in this case.

在这种情况下,属性被称为“属性”或“类成员”。

回答by David Morrow

this is a static class but, the same principle would go for an intantiated one as well. this lets you store and retrieve whatever you want from this class. and throws an error if you try to get something that is not set.

这是一个静态类,但同样的原则也适用于一个拟定的类。这使您可以从此类中存储和检索您想要的任何内容。如果您尝试获取未设置的内容,则会引发错误。

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 ]; 
}
}