有没有办法在当前类之外的类中调用方法?举个例子:
class firstclass
{
function method1()
{
return "foo";
}
}
class secondclass
{
function method2()
{
$myvar = firstclass::method1;
return $myvar;
}
}
$myvar = firstclass::method1;
试图访问firstclass方法1
此示例中的所需结果为$myvar = "foo"
。
我知道我可以使用“扩展”,但是想知道是否有办法在没有“扩展”的情况下做到这一点?
答案 0 :(得分:3)
假设method1
是静态方法,您只需要括号。这就像正常的函数调用一样。
$myvar = firstclass::method1();
顺便说一句,如果除了返回$myvar
之外没有对return firstclass::method1();
做任何其他事情,您可以将方法缩短为一行代码:
extends
secondclass
关键字的用途适用于您希望firstclass
继承secondclass extends firstclass
的属性和方法的时间。换句话说,您在两个类之间建立父子关系。如果它们根本不相关,那么您不应该声明{{1}}。您仍然可以通过简单地引用其类名来使用其他类范围内的任一类。
答案 1 :(得分:1)
在方法调用中添加()
function method2()
{
$myvar = firstclass::method1();
return $myvar;
}
OR
function method2()
{
$firstObj= new firstclass();
$myvar = $firstObj->method1();
return $myvar;
}
答案 2 :(得分:1)
class firstclass
{
public static function method1()
{
return "foo";
}
}
class secondclass
{
public function method2()
{
$myvar = firstclass::method1();
return $myvar;
}
}
答案 3 :(得分:0)
您的源代码不是面向对象编程的好例子。
你应该总是将firstclass
传递给secondclass
,例如使用构造函数。然后,您可以在first class
内调用secondclass
。
class firstclass
{
function method1()
{
return "foo";
}
}
class secondclass
{
/**
* @var firstclass
*/
private $firstClass;
/**
* @param firstclass $firstClass
*/
public function __construct(firstclass $firstClass)
{
$this->firstClass = $firstClass;
}
function method2()
{
return $this->firstClass->method1();
}
}
print_r((new secondclass(new firstclass))->method2());
如果您不想在firstclass
内使用secondclass
可调用的整个实例,然后调用它。
class firstclass
{
function method1()
{
return "foo";
}
}
class secondclass
{
/**
* @var callable
*/
private $method1;
/**
* @param callable $method1
*/
public function __construct(callable $method1)
{
$this->method1 = $method1;
}
function method2()
{
return call_user_func($this->method1);
}
}
print_r((new secondclass(array(new firstclass, 'method1')))->method2());
class firstclass
{
static function method1()
{
return "foo";
}
}
print_r((new secondclass('firstclass::method1'))->method2());