Bar O Kurniawan Bar O Kurniawan - 4 months ago 6
PHP Question

How to make a class stored data to a variable an callback with method?

I am interested in how this works:

<?php
$Query = $mysqli->query("select * from table");
$Query->fetch_array(); // <== How to make $Query a class/method like this?
?>


How do you assign a method to a variable and then have that variable be able to call another method like the
$mysqli
and
$Query
example above?

Answer

One way to achieve what you are (I think) referring to, is by returning an object. It goes against the principle of dependency injection, but it's one way to do it.

class MyClassA
    {
        public function myFunction()
            {
                return new MyClassB();
            }
    }

class MyClassB
    {
        public function execute()
            {
                return true;
            }
    }

// Start use
$class  = new MyClassA();
// Assign variable to function which returns object
$newObj = $class->myFunction();
// Will write "1" because now $newObj is MyClassB()
echo $newObj->execute();

Another way is to return $this from the first method. The usage of the above object would work identical in this instance, however you also allow another principle known as method chaining:

class MyClassA
    {
        public function myFunction()
            {
                return $this;
            }

        public function execute()
            {
                return true;
            }
    }

// Same as above works
$class  = new MyClassA();
$sameObj = $class->myFunction();
echo $sameObj->execute();

// Allowing for Method Chain
$class  = new MyClassA();
// Allowing for chaining
echo $class->myFunction()->execute();
Comments