Jonathan de M.
Jonathan de M.

Reputation: 9808

Check whether a method has been called if not call a specific method

I'd like to call a method if no method has been called, concrete example:

file foo.php would only contains

$p = new Foo();

the fact that no method is called would trigger a specific method.

file foo.php would now contains

$p = new Foo();
$p->bar();

this would not trigger the specific method since a method is called.

The point to do that would be to display help for user who use my class when they start.

Also I was thinking to use __destruct() but I'm not too sure when destruct is called.

Upvotes: 1

Views: 2138

Answers (2)

Fluffeh
Fluffeh

Reputation: 33512

As per DaveRandoms amazing comment:

class fooby
{
    private $hasCalled=false;

    function __destruct()
    {
        if(!$this->hasCalled)
        {
            // Run whatever you want here. No method has been called.
            echo "Bazinga!";
        }
    }

    public function someFunc()
    {
        $this->hasCalled=true;
        // Have this line in EVERY function in the object.
        echo "Funky Monkey";
    }
}

$var1 = new fooby();
$var1->someFunc(); // Output: Funky Monkey
$var1 = null; // No triggered trickery.

$var2= new fooby();
$var2 = null; // Output: Bazinga!

Upvotes: 4

s.webbandit
s.webbandit

Reputation: 17000

__destruct() is correct.

class Foo {

     private $method_invoked = false;

     public function bar(){
         $this->method_invoked = true;
         print 'bar';
     }

     function __destruct(){
         if(!$this->method_invoked) {
             print 'destr'; 
         }
     }

}

Upvotes: 3

Related Questions