【问题标题】:Getting model name from model instance YII从模型实例 YII 中获取模型名称
【发布时间】:2010-05-13 07:45:03
【问题描述】:

如何从模型实例中获取模型名称。 例如

$model=新状态;

这里, 状态是模型 $model 是状态模型实例。

我想从 $model 即模型实例中获取模型名称,即状态。

【问题讨论】:

标签: php yii


【解决方案1】:

将此方法添加到您的状态类

public function getModelName()
{
    return __CLASS__;
}

然后这样称呼它:

$model = new State();
echo $model->getModelName();

【讨论】:

  • 嗨@Wager,我更喜欢toninoj,为什么你现在不接受一个真实的答案?
【解决方案2】:

get_class() — 返回对象的类名

字符串 get_class ([ 对象 $object ] )

因此你可以这样使用它:$modelname=get_class($modelinstance);

->它返回一个字符串。

【讨论】:

  • 我更喜欢这种方法。无需扩展模型,因为 get_class 内置于 php php.net/manual/en/function.get-class.php
  • 这个效率更高,如果你有12个模型,我们不能写12个函数来获取它们的名字。
  • 如果你的类在某个命名空间中,可以使用 basename(get_class($object))
【解决方案3】:

使用这个 PHP 方法:get_class

 print get_class($object);

【讨论】:

    【解决方案4】:
    <?php
    
    class Item extends CActiveRecord
    {
    
        public function getBaseModelName()
        {
            return __CLASS__;
        }
    
        public function getCalledClassName()
        {
            return get_called_class();
        }
    }
    
    class Product extends Item {}
    
    class Service extends Item {}
    
    class ProductController extends CController
    {
        $model = new Product;
        echo $model->baseModelName; // Item
    }
    
    class ServiceController extends CController
    {
        $model = new Service;
    
        echo $model->calledClassName; // Service 
        echo get_class($model); // Service 
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 2012-03-29
      • 2018-04-12
      • 2013-11-06
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 2020-04-08
      相关资源
      最近更新 更多