"元对象"?

use*_*103 3 php oop

我想做这样的事情:

class StrangeClass {

    public function somethingLikeAMethod($var) {
        /* ... */
    }

    public function awesomeTest() {
        /* ... */
    }

}

$obj = new StrangeClass;
$ex1 = $obj->somethingLikeAMethod(1);

$ex2 = $obj->somethingLikeAMethod(2);

$ex1 -> awesomeTest(); // This will output "1"
$ex2 -> awesomeTest(); // This will output "2"
Run Code Online (Sandbox Code Playgroud)

换句话说,我希望该对象改变其行为.

在Lua语言中,我可以使用'metatables'来制作它,但我不知道如何在OO-PHP中制作它.谢谢.

添加:

我在Lua做了类似的事:

local query = Database.query(...) -- now this variable has a query id
local query2 = Database.query(...) -- this is a other query id

local result = query.fetchAssoc() -- read below
local result2 = query.fetchAssoc() -- I called the same object with same method twice, but it will return other results
Run Code Online (Sandbox Code Playgroud)

添加#2:

我想做的事:

$db = new Database();

$firstResult = $db->query('SELECT * FROM `table`')->fetch_assoc();
$firstExample = $db->query("SELECT * FROM `table` WHERE `id` = '1'");
$secondExample = $db->query("SELECT * FROM `table` WHERE `id` = '2'");

$secondResult = $firstExample -> fetch_assoc();
$thirdResult = $secondExample -> fetch_assoc();
Run Code Online (Sandbox Code Playgroud)

Pri*_*ner 8

天知道你为什么要这样,但这对你有用:

class StrangeClass {

    public function somethingLikeAMethod($var) {
        $this->test_var = $var;
        return clone $this;
    }

    public function awesomeTest() {
        echo $this->test_var;
    }

}

$obj = new StrangeClass;
$ex1 = $obj->somethingLikeAMethod(1);

$ex2 = $obj->somethingLikeAMethod(2);

$ex1->awesomeTest(); // This will output "1"
$ex2->awesomeTest(); // This will output "2"
Run Code Online (Sandbox Code Playgroud)

编辑:如果您正在寻找排队系统,您可以将每个查询推送到一个数组,如:

class StrangeClass {

    private $queries = array();

    public function somethingLikeAMethod($var) {
        $this->queries[] = $var;
        return $this;
    }

    public function awesomeTest() {
        if(count($this->queries) === 0){
            echo 'no queries left';
        }
        echo $this->queries[0];
        array_splice($this->queries,0,1);
    }

}

$obj = new StrangeClass;
$ex1 = $obj->somethingLikeAMethod("select * from hello");
$ex2 = $obj->somethingLikeAMethod("select * from me");
$ex2 = $obj->somethingLikeAMethod("select * from you");
$ex2 = $obj->somethingLikeAMethod("select * from my_friend");

$ex1->awesomeTest();
$ex2->awesomeTest();
$ex2->awesomeTest();
$ex2->awesomeTest();
$ex2->awesomeTest();
Run Code Online (Sandbox Code Playgroud)