Jump to content

Functions in _init seems to be a bad idea


joe_g
 Share

Recommended Posts

Hello,

I've been putting global functions in _init.php for quite a while. However when doing a wire404(); _init.php is called again and i get a functions redeclared error.

but _init.php seems to be made for this purpose? Is this a bug or did I misunderstand?

Link to comment
Share on other sites

Hello @joe_g

Yes I don't think this is a good place to define functions. When calling wire404(), a new template is rendered (page-404), so _init file is called again.

But you may do it with a constant:

if (!defined('FUNCTIONS_INITIALIZED')) {

    function test():void {
        echo "Hello";
    }

    define('FUNCTIONS_INITIALIZED', true);
}

For global functions I prefer to create static classes in different packages, each class for a single context.

When using custom Page classes, it's also possible to add this functions as methods in a base MyCustomPage class, and call them with $page->myMethod().

Link to comment
Share on other sites

I can't test this right now, but it might be simpler to put your functions in a separate file (e.g '_funcs.php') and then in '_init.php'  use:

// in _init.php

require_once '_funcs.php';

By using 'require_once', it shouldn't matter how many times '_init.php' gets called, the '_funcs.php' file will only be included once.

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...