2010-05-13 85 views
8

如何从模型实例获取模型名称。 适用于e.x.从模型实例获取模型名称YII

$ model = new State;

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

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

+0

工作示例与解释:http://code2real.blogspot.in/2015/06/yii-11-get-current-model-name。 html – Pupil 2015-06-09 10:18:53

回答

11

get_class() - 返回一个对象的类名

串get_class ([object $ object])

因此,您可以像这样使用它:$ modelname = get_cl屁股($ modelinstance);

- >它返回一个字符串。

+2

我更喜欢这种方法。没有必要扩展模型,因为get_class内置到php http://php.net/manual/en/function.get-class.php – sdjuan 2013-01-22 20:10:35

+0

这个更有效率,如果你有12个模型,我们不能写12函数来获取他们的名字。 – Pupil 2015-05-29 06:59:51

14

此方法添加到您的国家A级

public function getModelName() 
{ 
    return __CLASS__; 
} 

,并调用它像这样:

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

Thanx Wolax。它的工作原理 – 2010-05-13 12:37:16

+0

Hi @Wager,我更喜欢toninoj,为什么你现在不接受答案? – HPM 2013-05-13 09:30:01

1

使用此方法PHP:get_class

print get_class($object); 
0
<?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 
}