php - Why pass variables to a class instead of method -
i wondering benefit of passing parameters class rather method.
in terms of code, what's benefit of doing this:
$books = new books($book_id, $book_name);
instead of
$books = new books; $books->setbook($book_id, $book_name);
thanks!
"passing class" not thing. new foo($bar, $baz)
instantiating new object , passing parameters constructor method:
class foo { public function __construct($bar, $baz) { ... } }
there's no difference such between passing parameters regular method , constructor. difference constructor called when object instantiated, , other methods called anytime later.
you should pass parameters constructor object requires @ construction time. typically means pass parameters required object work @ all. constructor can throw exception if doesn't parameters, means object fail instantiate @ all. guarantees object in known, consistent state. compare:
$api = new fooapi($id, $password); $api->dosomething(); $api = new fooapi; // $api->setid($id); // $api->setpassword($password); $api->dosomething(); // error! no id , password given
Comments
Post a Comment