dongqiao3927
2010-03-26 02:17
浏览 27
已采纳

OOP - 处理类的自动实例 - PHP

This is a topic that, as a beginner to PHP and programming, sort of perplexes me. I'm 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!

图片转代码服务由CSDN问答提供 功能建议

这是一个主题,作为PHP和编程的初学者,让我感到困惑。 我正在建立一个股票市场网站,并希望用户添加自己的股票。 我可以清楚地看到每个股票都是一个具有类的所有方法的类实例的好处。 我难以理解的是在实例化时为该实例提供名称的最佳方法。 如果我有:

  class Stock(){
 ...... ....做的事情..... 
   
 
  

}

给我的实例命名的最佳方法是什么。 显然我可以写:

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

或其他什么,但如果用户通过应用程序添加股票,该实例的名称可以来自哪里? 我想总是使用$ newStock = new Stock()创建一个新的孩子,然后将其存储到数据库中,这将导致我下一个问题!

将20个用户股票(例如)检索到类Stock()的实例中的最佳方法是什么? 每次用户登录时是否需要实例化20个类Stock()的新实例?或者我缺少什么?

我希望有人能够回答这个问题,更重要的是希望一群人能够回答这个问题并以某种方式帮助那些正在努力解决可能导致真正优雅解决方案的人 。 多谢你们!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • drc4925 2010-03-26 03:52
    已采纳

    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();
    
    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题