php:如何使类中的方法运行?
我开始学习 oop php,但我不明白如何使类中的方法执行。 这是代码:
class GrabData {
public $tables=array();
public $columns=array();
public $argList;
function __construct(){
$this->argList=func_get_args();
$pattern;
var_dump($this->argList);
if(!empty($this->argList)){
foreach($this->argList as $value){
if(preg_match("/.+_data/",$value,$matches)){
if(!in_array($matches[0],$this->tables)){
array_push($this->tables,$matches[0]);
var_dump($this->tables);
}
$pattern="/". $matches[0] . "_" . "/";
array_push($this->columns,preg_replace($pattern,"",$value));
var_dump($this->columns);
}
}
}
}
public function gen_query(){
var_dump($this->argList);
echo "haha";
}
gen_query();
}
new GrabData("apt_data_aptname");
现在,当我创建一个新的 GrabData 对象时,__construct
函数会运行,但 gen_query
函数不会执行。我如何让它执行它?
I started learning oop php and I don't understand how to make a method inside a class execute.
This is the code:
class GrabData {
public $tables=array();
public $columns=array();
public $argList;
function __construct(){
$this->argList=func_get_args();
$pattern;
var_dump($this->argList);
if(!empty($this->argList)){
foreach($this->argList as $value){
if(preg_match("/.+_data/",$value,$matches)){
if(!in_array($matches[0],$this->tables)){
array_push($this->tables,$matches[0]);
var_dump($this->tables);
}
$pattern="/". $matches[0] . "_" . "/";
array_push($this->columns,preg_replace($pattern,"",$value));
var_dump($this->columns);
}
}
}
}
public function gen_query(){
var_dump($this->argList);
echo "haha";
}
gen_query();
}
new GrabData("apt_data_aptname");
Now, the __construct
function runs when I make a new GrabData object, but the gen_query
function doesnt execute. How do I make it execute it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,将 new 运算符返回的对象分配给一个变量 - 然后使用该变量在对象上执行方法:
First, you assign the object returned by the
new
operator to a variable - then use that variable to execute methods on your object:在不启动类的情况下运行类函数的另一种方法是使用双冒号范围解析运算符,奇怪地称为“Paamayim Nekudotayim”。
您可以在此处阅读它。
A different way to run a class function without initiating the class is to use the double colon scope resolution operator, strangely called "Paamayim Nekudotayim".
You can read up on it here.
如果您总是希望在类启动时运行 gen_query 函数,您可以在构造函数的底部链接到它,如下所示:
If you always want to have the
gen_query
function run when the class is initiated, you could link to it in the bottom of your constructor, like so: