类的Codeigniter方法-未定义函数

时间:2018-08-02 18:46:53

标签: codeigniter

我会尝试使用代码点火器进行第一步,因此我在现有的类中编写了一个新的methode(function)。

    <?php

defined('BASEPATH') or exit('No direct script access allowed');

class App
{
    /**
     * Options autoload=1
     * @var array
     */
    private $options = [];

    /**
     * Quick actions create aside
     * @var array
     */
    private $quick_actions = [];

    /**
     * CI Instance
     * @deprecated 1.9.8 Use $this->ci instead
     * @var object
     */
    private $_instance;

    /**
     * CI Instance
     * @var object
     */
    private $ci;

    /**
     * Show or hide setup menu
     * @var boolean
     */
    private $show_setup_menu = true;

    /**
     * Available reminders
     * @var array
     */
    private $available_reminders = ['customer', 'lead', 'estimate', 'invoice', 'proposal', 'expense', 'credit_note'];

    /**
     * Tables where currency id is used
     * @var array
     */
    private $tables_with_currency = [];

    /**
     * Media folder
     * @var string
     */
    private $media_folder;

    /**
     * Available languages
     * @var array
     */
    private $available_languages = [];

    public function __construct()
    {
        $this->ci = & get_instance();
        // @deprecated
        $this->_instance = $this->ci;

        $this->init();

        do_action('app_base_after_construct_action');
    }

    /**
     * Check if database upgrade is required
     * @param  string  $v
     * @return boolean
     */
    public function is_db_upgrade_required($v = '')
    {
        if (!is_numeric($v)) {
            $v = $this->get_current_db_version();
        }

        $this->ci->load->config('migration');
        if ((int) $this->ci->config->item('migration_version') !== (int) $v) {
            return true;
        }

        return false;
    }

    /**
     * Return current database version
     * @return string
     */
    public function get_current_db_version()
    {
        $this->ci->db->limit(1);

        return $this->ci->db->get('tblmigrations')->row()->version;
    }

    /**
     * Upgrade database
     * @return mixed
     */
    public function upgrade_database()
    {
        if (!is_really_writable(APPPATH . 'config/config.php')) {
            show_error('/config/config.php file is not writable. You need to change the permissions to 755. This error occurs while trying to update database to latest version.');
            die;
        }

        $update = $this->upgrade_database_silent();

        if ($update['success'] == false) {
            show_error($update['message']);
        } else {
            set_alert('success', 'Your database is up to date');

            if (is_staff_logged_in()) {
                redirect(admin_url(), 'refresh');
            } else {
                redirect(site_url('authentication/admin'));
            }
        }
    }

    /**
     * Make request to server to get latest version info
     * @return mixed
     */
    public function get_update_info()
    {
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_USERAGENT      => $this->ci->agent->agent_string(),
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_URL            => UPDATE_INFO_URL,
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => [
                'update_info'     => 'true',
                'current_version' => $this->get_current_db_version(),
            ],
        ]);

        $result = curl_exec($curl);
        $error  = '';

        if (!$curl || !$result) {
            $error = 'Curl Error - Contact your hosting provider with the following error as reference: Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl);
        }

        curl_close($curl);

        if ($error != '') {
            return $error;
        }

        return $result;
    }

    /**
     * Return all available languages in the application/language folder
     * @return array
     */
    public function get_available_languages()
    {
        $languages = $this->available_languages;

        return do_action('before_get_languages', $languages);
    }

    /**
     * Function that will parse table data from the tables folder for amin area
     * @param  string $table  table filename
     * @param  array  $params additional params
     * @return void
     */
    public function get_table_data($table, $params = [])
    {
        $hook_data = do_action('before_render_table_data', [
            'table'  => $table,
            'params' => $params,
        ]);

        foreach ($hook_data['params'] as $key => $val) {
            $$key = $val;
        }

        $table = $hook_data['table'];

        $customFieldsColumns = [];

        $path = VIEWPATH . 'admin/tables/' . $table . '.php';

        if (file_exists(VIEWPATH . 'admin/tables/my_' . $table . '.php')) {
            $path = VIEWPATH . 'admin/tables/my_' . $table . '.php';
        }

        include_once($path);

        echo json_encode($output);
        die;
    }


      /**
     * Check if a option value is preset or individual
     * @param  string $name, string $value
     * @return true/false
     */
    public function option_is_preset($name,$value)
    {
                $str="`name`='".$name."' and value='".$value."' ";
            $this->ci->db->select('id, name, value');
            $this->ci->db->where($str);
            $row = $this->ci->db->get('4U_tbloptions_preset')->row_array();

                if ($row['id']>0) {
                    return true;
                }

            return false;
    }    


    /**
     * All available reminders keys for the features
     * @return array
     */
    public function get_available_reminders_keys()
    {
        return $this->available_reminders;
    }

    /**
     * Get all db options
     * @return array
     */
    public function get_options()
    {
        return $this->options;
    }

    /**
     * Function that gets option based on passed name
     * @param  string $name
     * @return string
     */
    public function get_option($name)
    {
        if ($name == 'number_padding_invoice_and_estimate') {
            $name = 'number_padding_prefixes';
        }

        $val  = '';
        $name = trim($name);


        if (!isset($this->options[$name])) {
            // is not auto loaded
            $this->ci->db->select('value');
            $str="`name`='".$name."' and `maccid`='".$this->ci->session->userdata('macc_id')."'";
            $this->ci->db->where($str);
            $row = $this->ci->db->get('4U_accounts_tbloptions')->row();
            if ($row) {
                #echo"Wert aus account_tbloptions";
                $val = $row->value;
            }
        } else {
               #echo $name.'->'.$val.' Autoload - nicht aus DB!<br>';
            $val = $this->options[$name];
        }

        $hook_data = do_action('get_option', ['name' => $name, 'value' => $val]);

          //Fallback auf Standardwert
          if ($hook_data['value']=='')
          {
                $this->ci->db->select('value');
            $this->ci->db->where('name', $name);
            $row = $this->ci->db->get('4U_tbloptions_preset')->row();
            if ($row) {
                 #echo"Wert aus preset";
                $val = $row->value;
            }
              $hook_data = do_action('get_option', ['name' => $name, 'value' => $val]);
          }

        return $hook_data['value'];
    }

    /**
     * Add new quick action data
     * @param array $item
     */
    public function add_quick_actions_link($item = [])
    {
        $this->quick_actions[] = $item;
    }

    /**
     * Quick actions data set from admin_controller.php
     * @return array
     */
    public function get_quick_actions_links()
    {
        $this->quick_actions = do_action('before_build_quick_actions_links', $this->quick_actions);

        return $this->quick_actions;
    }

    /**
     * Aside.php will set the menu visibility here based on few conditions
     * @param int $total_setup_menu_items total setup menu items shown to the user
     */
    public function set_setup_menu_visibility($total_setup_menu_items)
    {
        $this->show_setup_menu = $total_setup_menu_items == 0 ? false : true;
    }

    /**
     * Check if should the script show the setup menu or not
     * @return boolean
     */
    public function show_setup_menu()
    {
        return do_action('show_setup_menu', $this->show_setup_menu);
    }

    /**
     * Return tables that currency id is used
     * @return array
     */
    public function get_tables_with_currency()
    {
        return do_action('tables_with_currency', $this->tables_with_currency);
    }

    /**
     * Return the media folder name
     * @return string
     */
    public function get_media_folder()
    {
        return do_action('get_media_folder', $this->media_folder);
    }

    /**
     * Upgrade database without throwing any errors
     * @return mixed
     */
    private function upgrade_database_silent()
    {
        $this->ci->load->config('migration');

        $beforeUpdateVersion = $this->get_current_db_version();

        $this->ci->load->library('migration', [
            'migration_enabled'     => true,
            'migration_type'        => $this->ci->config->item('migration_type'),
            'migration_table'       => $this->ci->config->item('migration_table'),
            'migration_auto_latest' => $this->ci->config->item('migration_auto_latest'),
            'migration_version'     => $this->ci->config->item('migration_version'),
            'migration_path'        => $this->ci->config->item('migration_path'),
        ]);
        if ($this->ci->migration->current() === false) {
            return [
                'success' => false,
                'message' => $this->ci->migration->error_string(),
            ];
        }
        update_option('upgraded_from_version', $beforeUpdateVersion);

        return [
                'success' => true,
            ];
    }

    /**
     * Init necessary data
     */
    protected function init()
    {

            //Autoloadfelder zuerst alle Presetfelder, die dann mit den Individualfeldern ueberschrieben werden
            $optionsA = $this->ci->db->select('name, value')
                ->where('autoload', 1)
            ->get('4U_tbloptions_preset')->result_array();          

            $str=" 'maccid'='".$this->ci->session->userdata('macc_id')."' AND 'autoload'='1' ";
            $optionsB = $this->ci->db->select('name, value')
                ->where($str)
            ->get('4U_accounts_tbloptions')->result_array(); 

            $options=array_merge($optionsA, $optionsB);       


        // Loop the options and store them in a array to prevent fetching again and again from database
        foreach ($options as $option) {
            $this->options[$option['name']] = $option['value'];
        }

        /**
         * Available languages
         */
        foreach (list_folders(APPPATH . 'language') as $language) {
            if (is_dir(APPPATH . 'language/' . $language)) {
                array_push($this->available_languages, $language);
            }
        }

        /**
         * Media folder
         * @var string
         */
        $this->media_folder = do_action('before_set_media_folder', 'media');

        /**
         * Tables with currency
         * @var array
         */
        $this->tables_with_currency = [
            [
                'table' => 'tblinvoices',
                'field' => 'currency',
            ],
            [
                'table' => 'tblexpenses',
                'field' => 'currency',
            ],
            [
                'table' => 'tblproposals',
                'field' => 'currency',
            ],
            [
                'table' => 'tblestimates',
                'field' => 'currency',
            ],
            [
                'table' => 'tblclients',
                'field' => 'default_currency',
            ],
            [
                'table' => 'tblcreditnotes',
                'field' => 'currency',
            ],
            [
                'table' => 'tblsubscriptions',
                'field' => 'currency',
            ],
        ];
    }

    /**
     * Predefined contact permission
     * @deprecated 1.9.8 use get_contact_permissions() instead
     * @return array
     */
    public function get_contact_permissions()
    {
        return get_contact_permissions();
    }
}

现在我想像这样使用这种方法

echo"Test1: ".get_option('company_logo_dark');
echo"Test2: ".option_is_preset('company_logo_dark');

方法“ get_option”是该类中现有的方法之一。

此方法(get_option)有效,但option_is_present会产生错误“调用未定义的函数option_is_preset()“

如果我尝试

echo "Test3: ".$this->app->option_is_preset('company_logo',$company_logo);

它将起作用。

为什么我可以用这种方法使用第一个方法“ get_option”(echo“ Test:” .get_option(string);“,为什么我不能对其他方法使用相同的方法?

非常感谢我的支持:-)

2 个答案:

答案 0 :(得分:0)

内部类中,您需要使用伪变量 $ this

echo"Test1: ". $this->get_option('company_logo_dark');
echo"Test2: ". $this->option_is_preset('company_logo_dark', 'some_value');

取消类的实例:

$instance = new App();
echo"Test1: ". $instance ->get_option('company_logo_dark');
echo"Test2: ". $instance ->option_is_preset('company_logo_dark', 'some_value');

如果将App类放置在库目录中,则可以使用Codeigniter Loader Class

$this->load->library('app');
echo"Test1: ". $this->app->get_option('company_logo_dark');
echo"Test2: ". $this->app->option_is_preset('company_logo_dark', 'some_value');

编辑1

get_option 方法只能在类外部声明时直接调用。请参阅下一个示例

function method_a($var) {
    echo __METHOD__ . ' : ' . $var .'<br />';
}
class MyClass {
    public function method_a($var) {
        echo __METHOD__ . ' : ' . $var .'<br />';
        $this->method_b($var);
    }
    public function method_b($var) {
        echo __METHOD__ . ' : ' . $var .'<br />';
    }
}
$instance = new MyClass();
$instance->method_a("Test");
method_a("Test");

这将返回:

MyClass::method_a : Test
MyClass::method_b : Test
method_a : Test

编辑2

根据更新后的类,方法option_is_preset带有两个参数$name$value,而您试图仅使用一个参数调用

echo"Test2: ".option_is_preset('company_logo_dark'); // wrong
echo"Test2: ".option_is_preset('company_logo_dark', 'some_value'); // correct

答案 1 :(得分:0)

在另一个文件中,我发现了

function get_option($name)
{
    $CI = & get_instance();
    if (!class_exists('app')) {
        $CI->load->library('app');
    }

    return $CI->app->get_option($name);
}

这说明了为什么可以通过函数的常规方式调用“ get_option”。

所以我添加了

function option_is_preset($name, $value)
{
    $CI = & get_instance();
    if (!class_exists('app')) {
        $CI->load->library('app');
    }

    return $CI->app->option_is_preset($name, $value);
}

现在我可以像函数一样调用新方法了:-))