Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to instantiate the called class instead of the CActiveRecord class #4532

Closed
wants to merge 1 commit into from

Commits on Aug 29, 2023

  1. Allow to instantiate the called class instead of the Ar class

    The problem of this implementation is that this method needs to copied onto the children class to be instantiated correctly, since if the method is inherited __CLASS__ will always point to CActiveRecord instead of the class calling this method
    
    This change allows that if
    
    class A extends CActiveRecord {}
    
    And we call A::model(), we will get an A instance instead of CActiveRecord
    
    <?php
    
    class B
    {
    	public static function model($className = __CLASS__)
        {
            return new $className(null);
        }	
    }
    
    class A extends B
    {
    	
    }
    
    $b = new B();
    $a = new A();
    
    var_dump($b::model());
    var_dump($a::model());
    
    returns
    
    object(B)yiisoft#3 (0) { } object(B)yiisoft#3 (0) { } 
    
    but if we change that to get_called_class()
    
    class B
    {
    	public static function model($className = null)
        {
    		if($className === null){
    			$className = get_called_class();
    		}
    		
            return new $className(null);
        }	
    }
    
    class A extends B
    {
    	
    }
    
    $b = new B();
    $a = new A();
    
    var_dump($b::model());
    var_dump($a::model());
    
    results in
    
    object(B)yiisoft#3 (0) { } object(A)yiisoft#3 (0) { }
    eduardor2k authored Aug 29, 2023
    Configuration menu
    Copy the full SHA
    3279c0a View commit details
    Browse the repository at this point in the history