【发布时间】: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) 函数。
【问题讨论】:
-
我相信你的措辞可能有点。你调用一个类的方法,你访问一个类的属性,你实例化一个类。
-
在你的情况下,如果你想访问
&x,你可以使用:$newClass = new My_Looping_Class_Copy(); echo $newClass->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 的成员,您必须使其成为成员或派生类。