【问题标题】:Use an object property as a class name to call a method statically?使用对象属性作为类名来静态调用方法?
【发布时间】:2015-01-20 16:18:42
【问题描述】:

所以我有一个 Son 类的对象:

class Son extends Father {
    $_modelName = 'House';
}

另一个班级Daughter

class Daughter extends Father {
    $_modelName = 'Museum';
}

我希望他们的父类 Father 能够在他们各自的对象上调用静态方法。

class Father {
    public function foo() {
        $className = $this->_modelName;
        return $className::bar();
    }
}

编辑:基本上,我希望能够调用foo() 方法,并从相应的模型类中调用bar() 方法,避免使用额外的变量($className)?我试过{$this->_modelName}::bar() 没有成功。

【问题讨论】:

标签: php oop


【解决方案1】:

我认为这很难通过将模型名称作为字符串来实现,但也许您可以考虑一些不同的事情?

从 php 5 开始,我们可以将对象分配给变量without moving the entire object around

这意味着当您将modelName 分配给您的SonDaughter 类时,您可以轻松分配它...

...一堂课!

想象一下:

class Father {
  private $model;
  public function __construct($model) {
    $this->model = $model;
  }
  public function foo() {
    return $this->model->bar();
  }
}
class Son extends Father {
}
class Daughter extends Father {
}

这假定您使用此模型对象构造 SonDaughter 类。该函数不是静态的,因为我们需要一个构造函数来将模型分配给一个属性。

但您也可以考虑将模型传递给 `foo()` 函数:

public function foo($model) {
  return $model->bar();
}

关于dependency injection 原则,可以让您非常轻松地实现您的foo() 功能,并且比依赖于继承等一些复杂的设计问题要好得多。

您从该函数的依赖中解放出来,因为您可以将任何 $model 对象传递给 foo 方法。

【讨论】:

    【解决方案2】:

    或者你可以这样做:

    <?php
    
        class Son extends Father {
            protected $_modelName = 'House';
        }
    
        class Daughter extends Father {
           protected $_modelName = 'Museum';
        }
    
        class Father {
            protected $_modelName = 'Father';
            public function getModelName() {
                return $this->_modelName;
            }
        }
    
        $father =  new Father();
        $son = new Son;
        $daughter = new Daughter();
    
         echo $father->getModelName();
         echo $son->getModelName();
         echo $daughter->getModelName();
    ?>
    

    【讨论】:

    • 这不是我想做的,请检查编辑。
    猜你喜欢
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多