How to access a member function to a template file in WordPress?

  • Unknown's avatar

    I’m trying to build a WordPress theme with a lot of customizations. I’m trying to build it using the Object-Oriented approach so that I can create functions without worrying about naming them unique and I think it will be easier to bring in updates in the future.

    The problem that I’m facing is when I try to access one of the member functions using an object it returns errors.

    I tried with creating a global object to access the member function but it throws an error like this:

    
    Fatal error: Uncaught Error: Call to a member function distribute_numbers() on null.
    
    

    functions.php
    ———————

    if( ! defined( ‘ABSPATH’ )) {
    exit;
    }

    /**
    * Theme Calculations
    */
    require get_template_directory() . ‘/inc/calc.php’;

    inc/calc.php
    ———————–

    class Theme_Calc{
    public function distribute_numbers(){
    $array = [10, 9, 8, 6, 4,2];
    return $array;
    }
    }

    global $obj_calc;
    $obj_calc = new Theme_Calc();


    front-page.php
    ———————-

    </head>
    <body>

    <?php

    global $obj_calc;

    //$nums = Theme_Calc::distribute_numbers();

    $nums = $obj_calc->distribute_numbers();

    ?>

    This is a simplified version of what I’ve tried so far and every time when I try to access the member function on a template file, it gives me this error:

    Any help would be greatly appreciated.

    The blog I need help with is: (visible only to logged in users)

  • Unknown's avatar

    Hello

    These forums are for support to sites created on WordPress.com. I can see your site is self-hosted with an external provider.

    Please refer to this link to find out the differences between WordPress.com and WordPress.org here:: https://en.support.wordpress.com/com-vs-org/

    You may be able to find help here: https://wordpress.org/support/forums/ or contact your hosting provider.

    Regards:

  • The topic ‘How to access a member function to a template file in WordPress?’ is closed to new replies.