【问题标题】:PHP Classes - How to call them properlyPHP 类 - 如何正确调用它们
【发布时间】:2021-09-12 21:19:22
【问题描述】:

这是我很确定我能做到的,只是不知道该怎么做。

class My_Looping_Class {

   public function __construct() {
        $this->vars = new My_Vars_Class();  //maybe this goes here???
        for($y=0;$y<=10;$y++) {
             $this->do_loop();
        }
   }

   private function do_loop() {
    //in this loop the value of $x in My_Var_Class gets incremented each loop but I'm not exactly 
    //sure how to call it.  Something like this????
    $this->vars->x++;
   }
}

class My_Var_Class {

  public $x = 0;

}

class My_Looping_Class_Copy extends My_Looping_Class {
     // Here I need to be able to read and echo the value of x in My_Var_Class each time it 
     //changes but again, I'm unsure of how to call it.
}

new My_Looping_Class_Copy();

尝试仅使用上面的代码发布此内容,但它抱怨我没有足够的详细信息。所以,这里是:

我正在尝试做的是编写一个类似于 PHPCrawl 的网络爬虫。在 PHPCrawl 中,您基本上设置了爬虫的参数(爬取深度、跟随重定向、超时等),设置 url,在主类中调用“go”函数并开始爬取页面。当它爬取每个页面时,它会更新另一个包含所有结果变量的类,例如响应时间、找到的链接等。完成每个页面爬取后,通过类扩展,您可以访问所有这些变量并处理随你便。之后,它会爬取它找到的另一个 url 并更新结果变量。

我尝试通读代码,但很快就迷失了作者是如何做到的。上面的代码只是 PHPCrawl 工作原理的一个非常基本的示例。

这是 PHPCrawl 示例代码的链接:http://phpcrawl.cuab.de/example.html 我要复制的是 handleDocumentInfo($DocInfo) 函数。

【问题讨论】:

  • 我相信你的措辞可能有点。你调用一个类的方法,你访问一个类的属性,你实例化一个类。
  • 在你的情况下,如果你想访问&amp;x,你可以使用:$newClass = new My_Looping_Class_Copy(); echo $newClass-&gt;x;
  • 是的,术语总是让我感到困惑。对不起。所以我不明白。 $newClass->x 如何读取 My_Var_Class x?
  • 抱歉,我犯了一个错误$newClass = new My_Var_Class() 将创建一个具有x 属性的类的实例。
  • 您的代码中有 3 个类,其中 my_looping_class_copy 可以访问 my_looping_class 的公共和受保护成员,没有任何东西将 my_var_class 链接到任何东西,它是它自己的类,如果你想有权访问 my_var_class 的成员,您必须使其成为成员或派生类。

标签: php class


【解决方案1】:

如果我理解正确,这里有一个示例,说明如何获取一个类的属性值并在另一个类中使用它。扩展另一个,实例化它,并获得属性的新值:

class My_Looping_Class {
    
    public $xCopy;

    public function __construct() {
        $varClass = new My_Var_Class();
        $this->xCopy = $varClass->x + 10; // Here i add 10 to this class propert 'xCopy'. Loop or do whatever you want with it instead.  
   }
}

class My_Var_Class {

  public $x = 33; // Just some number as an example. 
}

class My_Looping_Class_Copy extends My_Looping_Class {
   
}

$loopClassCopy = new My_Looping_Class_Copy();

echo $loopClassCopy->xCopy; // Should output 43 (33 + 10)

或者看到这个working example

【讨论】:

  • 不完全是。您删除了 for 循环。这样做的目的是模拟爬虫索引网页。对于您的 $x=33 示例和循环类中的 for 循环,我希望输出为 33、34、35、36... 43。
  • $xCopy 是您班级的单个属性(具有单个值)。如果你想要多个值,要么将其放入一个数组中,要么拥有你的类的多个实例。希望这会有所帮助!
  • 感谢您的尝试。我想我只是无法很好地解释这一点。
  • 如果它爬取了 10000 个网页,在处理之前将 html、链接和其他数据存储在一个数组中,那么这个数组将是巨大的。这就是为什么每次循环时都需要 x 的输出,以便可以取消设置或重置为默认数字。
  • 好的,有一些工作要做,但它并不漂亮:3v4l.org/Qlsca 出于我的目的,我的逻辑在输出上是关闭的。这就是它的样子,因为 $x 需要在循环的每次迭代中重置回 0,所以它总是 = 1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2018-09-03
  • 2011-01-31
  • 2011-01-15
  • 2023-03-25
相关资源
最近更新 更多