Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatically call all method inside the class in php

Is there a way to call all the methods from a class once the class is initialized? For example, lets say I have a class named todo and once I make an instance of a todo class, all the methods/functions inside it will be executed, without calling it in the constructor?

<?php 
    class todo 
    {
        function a()
        {
        }
        function b()
        {
        }
        function c()
        {
        }
        function d()
        {
        }
    }

    $todo = new todo();
?>

In here I created an instance of a class todo so that the methods a, b, c, d will be executed. Is this possible?

like image 280
avien Avatar asked Aug 07 '26 21:08

avien


2 Answers

This outputs 'abc'.

class Testing
{
    public function __construct()
    {
        $methods = get_class_methods($this);

        forEach($methods as $method)
        {
            if($method != '__construct')
            {
                echo $this->{$method}();
            }
        }
    }

    public function a()
    {
        return 'a';
    }

    public function b()
    {
        return 'b';
    }

    public function c()
    {
        return 'c';
    }
}
like image 58
Sherlock Avatar answered Aug 10 '26 11:08

Sherlock


I think you can use iterator. All methods will be called in foreach PHP Iterator

like image 37
aDaemon Avatar answered Aug 10 '26 11:08

aDaemon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!