Jason Jason - 5 months ago 11
PHP Question

php OOP call to a method in a class outside the current class

Is there a way to call a method in a class outside of the current class? For an example:

class firstclass
{
function method1()
{
return "foo";
}
}
class secondclass
{
function method2()
{
$myvar = firstclass::method1;
return $myvar;
}
}


Where the
$myvar = firstclass::method1;
is an attempt to access the firstclass method1.

The desired result in this example would be
$myvar = "foo"
.

I know I could use "extend", but wanted to know if there was a way to do it without "extend"?

Answer

Assuming method1 is a static method, you just need parentheses. It's just like a normal function call.

$myvar = firstclass::method1();

Incidentally, if you don't do anything else with $myvar other than returning it, you can shorten your method into one line of code:

return firstclass::method1();

The purpose of the extends keyword is for when you want secondclass to inherit the properties and methods of firstclass. In other words, you establish a parent-child relationship between the two classes. If they're not related at all, then you should not declare secondclass extends firstclass. You can still make use of either class in the scope of other classes by simply referencing their class names.