Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

php - PDO - FETCH_CLASS - pass results to constructor as parameters

Is there any way, to pass results of PDO as parameters of the constructor? Let's say, I have the following class:

class Test
{
    private $value1;
    private $value2;
    function __construct($val1, $val2)
    {
        $this->value1 = $val1; $this->value2 = $val2;
    }
}

Then, via PDO driver I select some data from DB, let's say:

SELECT price, quantity FROM stock

$results = $query->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "Test");

Right now, PDO passess these values directly to the class fields, and bypassing the constructor.

Maybe I am missing something, but I want to pass results from the query to the constructor. Constructor cannot be query-dependent, I want to be able to instantiate this class even without using PDO.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only way I figured out was using FETCH_FUNC constant and providing a function to create the object through the constructor.

function rowMapper( $price, $quantity)
{
  return new Test( $price, $quantity);
}
$results = $query->fetchAll( PDO::FETCH_FUNC, "rowMapper");

Now your objects will only be created using your constructor, instead of having PDO injecting values in private data and breaking the encapsulation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...