在 php 中获取设置属性

2022-08-30 14:53:51

我来自C#环境,我开始在学校学习PHP。我习惯于像这样在C#中设置我的属性。

public int ID { get; set; }

在 php 中,这相当于什么?

谢谢。


答案 1

没有,尽管有一些关于在将来的版本中实现它的建议。现在,不幸的是,您需要手动声明所有 getter 和 setter。

private $ID;

public function setID($ID) {
  $this->ID = $ID;
}

public function getID() {
  return $this->ID;
}

对于一些魔术(PHP喜欢魔术),你可以查找和魔术方法。__set__get

class MyClass {

  private $ID;

  private function setID($ID) {
    $this->ID = $ID;
  }

  private function getID() {
    return $this->ID;
  }


  public function __set($name,$value) {
    switch($name) { //this is kind of silly example, bt shows the idea
      case 'ID': 
        return $this->setID($value);
    }
  }

  public function __get($name) {
    switch($name) {
      case 'ID': 
        return $this->getID();
    }
  }

}


$object = new MyClass();
$object->ID = 'foo'; //setID('foo') will be called

答案 2

谢谢大家的回答。它帮助我创建了这样的东西:

在我的父类中:

public function __get($name){

    if (ObjectHelper::existsMethod($this,$name)){
        return $this->$name();
    }

    return null;
}

public function __set($name, $value){

    if (ObjectHelper::existsMethod($this,$name))
        $this->$name($value);
}

ObjectHelper::existsMethod是一种方法,它只检查给定的受保护方法是否存在。

private $_propertyName = null;

protected function PropertyName($value = ""){

    if (empty($value)) // getter
    {
        if ($this-> _propertyName != null)
            return $this->_propertyName;
    }
    else // setter
    {
        $this-> _propertyName = $value;
    }

    return null;
}

所以我可以在任何类中使用这样的东西:

$class = new Class();
$class->PropertyName = "test";
echo $class->PropertyName;

我的灵感来自C#:)

伙计们,你们对此怎么看?

这是我的对象帮助者,如果有人想使用它:

namespace Helpers;

use ReflectionMethod;

class ObjectHelper {

public static function existsMethod($obj, $methodName){

    $methods = self::getMethods($obj);

    $neededObject = array_filter(
        $methods,
        function ($e) use($methodName) {
            return $e->Name == $methodName;
         }
    );

    if (is_array($neededObject))
        return true;

    return false;
}

public static function getMethods($obj){

    $var = new \ReflectionClass($obj);

    return $var->getMethods(ReflectionMethod::IS_PROTECTED);
}
}

推荐