13

How can i get model name from model instance. For e.x.

$model=new State;

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

I want to get model name i.e State from $model i.e model instance.

1

5 Answers 5

15

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I much prefer this method. There's no need to extend the model as get_class is built into php php.net/manual/en/function.get-class.php
This one is more efficient, in case you have 12 models, we cannot write 12 functions to get their names.
if your class is in some namespace, one might use basename(get_class($object))
15

add this method to your State Class

public function getModelName()
{
    return __CLASS__;
}

and call it like this:

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

1 Comment

Hi @Wager, Also I prefer toninoj more, why don't you accept an answer as true right now?
1

Use this PHP method : get_class

 print get_class($object);

Comments

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 
}   

Comments

0

To get State as the question asked, you may do this : -

basename(get_class($model))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.