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”?
Assuming
method1is a static method, you just need parentheses. It’s just like a normal function call.Incidentally, if you don’t do anything else with
$myvarother than returning it, you can shorten your method into one line of code:The purpose of the
extendskeyword is for when you wantsecondclassto inherit the properties and methods offirstclass. In other words, you establish a parent-child relationship between the two classes. If they’re not related at all, then you should not declaresecondclass extends firstclass. You can still make use of either class in the scope of other classes by simply referencing their class names.