• Andry

    (@blackstar1991)


    I had a test task. It was to display the results of the functions on the page page.php

    class MyClass {
        public function aaa () {
            echo "It's function aaa";
        }
        static public function bbb () {
            echo "It's function bbb";
        }
    }

    page.php I tried to get them through

    <?php class MyClass {
        public function aaa () {
            echo "It's function aaa";
        }
        static public function bbb () {
            echo "It's function bbb";
        }
    }
    ?>
    
    <h1><?php the_title?></h1>
    <p>Result function aaa = <b><?php add_action('init', 'MyClass::aaa'); ?></b></p>
    
    <p>Result function aaa = <b><?php 
    $my_class = new MyClass();
    add_action('init', [$my_class, 'bbb']); ?></b></p>

    but got nothing. What is the problem of this code ?

Viewing 3 replies - 1 through 3 (of 3 total)
  • threadi

    (@threadi)

    This is completely wrong:

    <?php the_title?>

    I guess you want to output the title of the page here. Then it would be correct:

    <?php echo the_title(); ?>

    Furthermore your code gives the following error message:

    Fatal error: Uncaught TypeError: call_user_func_array(): Argument #1 ($callback) must be a valid callback, non-static method MyClass::aaa() cannot be called statically

    Make sure you have these errors displayed in debug mode, then you will see them yourself faster during development. Solution for your case is: you mixed up your static and non-static function in the add_action() calls.

    Thread Starter Andry

    (@blackstar1991)

    Thanks. I understand that my code is not working. The question just also consists in that to receive values from a static and non-static function of a Сlass.

    <b><?php $a = add_action('init', 'MyClass::aaa'); echo $a; ?></b>
    threadi

    (@threadi)

    add_action has no return value other than true. Therefore, your call will not work in a meaningful way. See: https://developer.www.ads-software.com/reference/functions/add_action/

    Correct would be simply:

    add_action('init', 'MyClass::aaa');

    although it is questionable whether this is what you want to achieve. I cannot judge that.

    Maybe it would be good if you read again what the hooks are for: https://developer.www.ads-software.com/plugins/hooks/

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to show the result of executing a function from a Сlass’ is closed to new replies.