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!

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?