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

时间:2016-03-23 05:49:20

标签: php codeigniter

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

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), '"'), ':')
                ));
    }
}

他们都工作。

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

2 个答案:

答案 0 :(得分:1)

问题就像xmike所说的那样,没有加载Class_cast_helper类。

我将该类移到库文件夹下并在使用它之前加载它,

$this->load->library('Class_cast_helper');
这解决了我的问题。

答案 1 :(得分:0)

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

应用/核心/ 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), '"'), ':')
                ));
}