为什么从另一个类调用公共静态方法在CI中不起作用


Why calling a public static method from another class is not working in CI?

我使用CodeIgniter 2.2.6,我找到了将stdClass转换为另一个类的代码,并将其放入class_cast_helper中,并使转换方法为公共静态。

class Class_cast_helper {
    /**
     *
     * This method allows to cast stdClass to $className
     * @param unknown $instance
     * @param unknown $className
     */
    public static function objectToObject($instance, $className) {
        return unserialize(sprintf(
                'O:%d:"%s"%s',
                strlen($className),
                $className,
                strstr(strstr(serialize($instance), '"'), ':')
                ));
    }
}

但是当我用调用这个方法时

$newObj = Class_cast_helper::objectToObject($obj, "Event");

它不起作用。

如果我直接将该方法放入称为的类(MY_CI_Controller)中

class MY_CI_Controller extends CI_Controller {
    public function test(){
        $newObj = Class_cast_helper::objectToObject($obj, "Event"); // not work
        $newObj = MY_CI_Controller::objectToObject($obj, "Event"); // works
        $newObj = $this->objectToObject($obj, "Event"); // works
    }
    public static function objectToObject($instance, $className) {
        return unserialize(sprintf(
                'O:%d:"%s"%s',
                strlen($className),
                $className,
                strstr(strstr(serialize($instance), '"'), ':')
                ));
    }
}

他们都工作。

为什么该方法不能放在调用者类之外?

问题就像xmike所说的,class_cast_helper类没有加载。

我把那个类移到库文件夹下,在使用它之前加载它,

$this->load->library('Class_cast_helper');

这解决了我的问题。

当您需要创建一个扩展控制器时。

application/core/MY_Controller.php

<?php 
class MY_Controller extends CI_Controller {
  public function __construct() {
     parent::__construct();
     $this->load->helper('cast'); // load the helper
     // Then you can access function 
     // Just examples
     $this->test();
  }
  public function test(){
    $newObj = $this->cast->objectToObject($obj, "Event");
    $newObj = MY_Controller::objectToObject($obj, "Event");
 }

}

在控制器上你需要扩展它

文件名:example.php

<?php
class Example extends MY_Controller {
public function index() {
}
}

当你需要使用助手时,请确保你的助手文件名

application/helpers/cast_helper.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
public static function objectToObject($instance, $className) {
    return unserialize(sprintf(
                'O:%d:"%s"%s',
                strlen($className),
                $className,
                strstr(strstr(serialize($instance), '"'), ':')
                ));
}