S
S
Shimpanze2021-06-03 06:57:22
PHP
Shimpanze, 2021-06-03 06:57:22

I implement method chaining. How to make a method call affect the overall result?

Hello!

I actively learn OOP.

$foo = new foo;
$foo->bar( 'abc' );


Is it possible, inside the class foo, to find out that in this instance, the method is currently called bar()?

class foo {
    public function bar( $data ) {}

    private function baz() {
        if ( если вызван bar() ) {
            // сделать что-то
        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2021-06-03
@Shimpanze

Learn to ask questions. What you just wrote is called the XY problem , the scourge of all beginners. (and of course, the scourge of all the helpers on the toaster, who have no time to think, they need to answer the question).
Never ask the question of how to fix that crooked crutch that you invented for yourself out of illiteracy. Always ask the question how to solve the original problem.
Because it is solved in an elementary way. You just need to understand that OOP is not limited to "method calls". sometimes they even write some code in the methods. so getting attached to the fact of calling a method is just stupid. And information between methods in a class is passed using variables, that is, class properties

class foo {
    protected $bar;
    public function bar(string $data ) {
        $this->bar = $data; 
    }

    private function baz() {
        if (isset($this->bar)) {
            // сделать что-то
        }
    }
}

S
Sergey, 2021-06-03
@sslion

the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that

__FUNCTION__ returns only the name of the function

while as __METHOD__ returns the name of the class alongwith the name of the function

class trick
{
      function doit()
      {
                echo __FUNCTION__;
      }
      function doitagain()
      {
                echo __METHOD__;
      }
}
$obj=new trick();
$obj->doit();
output will be ----  doit
$obj->doitagain();
output will be ----- trick::doitagain

R
Rsa97, 2021-06-03
@Rsa97

https://www.php.net/manual/ru/function.debug-backt...

class Baz
{
    public function bar() {
        $this->foo();
    }
    
    public function foo() {
        $backtrace = debug_backtrace();
        $stack = array_map(
            function($el) {
                return "{$el['class']}{$el['type']}{$el['function']}";
            },
            $backtrace
        );
        var_dump($stack);
    }
}

$t = new Baz;
$t->bar();

/* array(2) {
  [0] => string(8) "Baz->foo"
  [1] => string(8) "Baz->bar"
} */

But, for good, the behavior of the function should not depend on where it is called from.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question