简体   繁体   中英

Getting model name from model instance YII

How can i get model name from model instance. For ex

$model=new State;

here, State is model $model is State model instance.

I want to get model name ie State from $model ie model instance.

add this method to your State Class

public function getModelName()
{
    return __CLASS__;
}

and call it like this:

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

get_class() — Returns the name of the class of an object

string get_class ([ object $object ] )

therefore you use it like this: $modelname=get_class($modelinstance);

->it returns a string.

使用这个 PHP 方法: get_class

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

要获得所问问题的状态,您可以这样做:-

basename(get_class($model))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM