从同一个 PHP 类中的另一个方法调用一个方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2220809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling a method from another method in same PHP class
提问by Constant Meiring
I'm trying to use a method from within another method in a class. I don't have much experience in PHP5 OOP, and I looked around for answers, but couldn't find any. I'm trying to use getClientInfo() in sendRequest(), which is in the same class.
我正在尝试使用类中另一个方法中的方法。我在 PHP5 OOP 方面没有太多经验,我四处寻找答案,但找不到任何答案。我正在尝试在同一个类中的 sendRequest() 中使用 getClientInfo()。
class DomainHandler {
public static function getClientInfo($db, $client_id)
{
//Do stuff
}
public static function sendRequest($details)
{
require_once('MySQL.class.php');
$db = new MySQL;
getClientInfo($db, $client);
}
}
And it tells me:
它告诉我:
Fatal error: Call to undefined function getClientInfo()
致命错误:调用未定义的函数 getClientInfo()
I've also tried
我也试过
parent::getClientInfo($db, $client);
and
和
$this->getClientInfo($db, $client);
to no avail.
无济于事。
Any ideas?
有任何想法吗?
回答by Morfildur
It's a static method so you have to call it with self::getClientInfoor DomainHandler::getClientInfo.
这是一个静态方法,因此您必须使用self::getClientInfoor调用它DomainHandler::getClientInfo。
Also: You might want to read up on object oriented programming since it looks like you have not yet understood what it's really about (it's not just putting functions between a class Foo { and } and putting public static in front of them)
另外:您可能想阅读面向对象编程,因为您似乎还没有理解它的真正含义(这不仅仅是将函数放在类 Foo { 和 } 之间并将公共静态放在它们前面)
回答by Tatu Ulmanen
You are declaring the functions as staticand hence they are not in object context – you can call them with DomainHandler::getClientInfo()or self::getClientInfo().
您将函数声明为静态函数,因此它们不在对象上下文中——您可以使用DomainHandler::getClientInfo()或调用它们self::getClientInfo()。
If you don't explicitly need the functions to be static, you can drop the statickeyword and then $this->getClientInfo()will work.
如果您没有明确要求函数是静态的,您可以删除static关键字,然后$this->getClientInfo()就可以工作了。
回答by user187291
'self' is the keyword you're looking for
'self' 是您要查找的关键字
that said, can you explain why you need your methods to be static? "static" is poor style and should be avoided.
也就是说,你能解释为什么你需要你的方法是静态的吗?“静态”是糟糕的风格,应该避免。

