开发者

OOP - Handling Automated Instances of a Class - PHP

This is a topic that, as a beginner to PHP and programming, sort of perplexes me. I'开发者_如何学Gom building a stockmarket website and want users to add their own stocks. I can clearly see the benefit of having each stock be a class instance with all the methods of a class. What I am stumped on is the best way to give that instance a name when I instantiate it. If I have:

class Stock() {
   ....doing stuff.....

}

what is the best way to give my instances of it a name. Obviously I can write:

$newStock = new Stock();
$newStock.getPrice();

or whatever, but if a user adds a stock via the app, where can the name of that instance come from? I guess that there is little harm in always creating a new child with $newStock = new Stock() and then storing that to the DB which leads me to my next question!

What would be the best way to retrieve 20 user stocks(for example) into instances of class Stock()? Do I need to instantiate 20 new instances of class Stock() every time the user logs in or is there something I'm missing?

I hope someone answers this and more important hope a bunch of people answer this and it somehow helps someone else who is having a hard time wrapping their head around what probably leads to a really elegant solution. Thanks guys!


I would suggest doing something like:

class Stock()
{
   public var $symbol;

   public function __construct($symbol)
   {
      $this->symbol = $symbol;
   }

   public function lookup()
   {
       // do something
       return $data;
   }
}


$stock = new Stock('AAPL');
$data[] = $stock->lookup();

So you could just $stock->symbol = 'NEWSYMBOL'; and then $stock->lookup();


You can just use an array of stocks. Note that [] means add a new item to the array.

$stocks[] = new Stock();

You can iterate through all of them like this:

foreach ($stocks as $stock) {
    echo $stock->lookup();
}

You can access a particular stock like this:

$stocks[7]->display();


I don't understand why you wouldn't just make a Stock() object and have it load the various stock properties from a database. This seems a lot safer way to go and a lot less complicated to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜