0

Is it possible to do something like this one:

class conditional
    {

        function __construct()
        {
            if (launch() is called) {
                //return True 
                //function is called by class instance
            }else{
                //return False
                //launch() is not called
            }
        }

        public function launch(){
            echo "function is launcher";
        }
    }

I am trying to use a condition in class constructor to know if the class function is called by class instance or object as $class_instance->launch(). If the function is not called by class instance then it should run return else condition.

2
  • $class_instance->launch() doesn't trigger $class_instance::__construct method as you expect in the code above Commented Jan 21, 2017 at 16:17
  • @RomanPerekhrest So is there any other possible way to implement this one? Commented Jan 21, 2017 at 16:27

1 Answer 1

2

I don't think you can do what you want to do (nor I understand why would want to).

The constructor will run when you create the instance, before you are able to call any of the instance methods. Unless you have a way to delve into the future and know at instantiation time if any of the instance methods will be called later on, no dice :)

But you can do something that more or less looks like that using the __call magic method, even if probably doesn't make much sense in most scenarios.

E.g., a very simplified implementation:

class Magical {

   public function __call($method, $args) {

       switch($method) {
          case "launch":
             echo "magical launch() was called\n";
             $this->magicLaunch();
             break;
          default:
             throw new \Exception("Method not implemented");
       }
  }

  private function magicLaunch() {
      echo "magic!";
  }
}


// this is the only point where the constructor gets called
$magic = new Magical();

// since the launch method doesn't exist, the magic method __call is invoked
$magic->launch();

Outputs:

magical launch() was called

magic!

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is the thing that I am finding... Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.