# index.php
include "class1.php";
include "class2.php";
$class1 = new name1\Class1();
$class1->sayHello();
# class1.php
namespace name1;
use name2\Class2;
class Class1{
public function sayHello(){
echo Class2::staticFunction();
}
}
# class2.php
namespace name2;
class Class2{
public static function staticFunction(){
return "hello!";
}
}https://stackoverflow.com/questions/27990717/call-function-from-different-class-and-namespace
(new MyFunctions\basic)->say_hello("Bob");
(I dont recommend this method, it creates an object for no reason.)
What I'm assuming you wanted was:
namespace MyFunctions;
function say_hello($a)
{
echo "Hello, $a";
}
at which point you could use
// this gives you 'Hello, Bob'
https://stackoverflow.com/questions/27994852/using-function-inside-php-namespace
Calling static vs dynamic
public function foo()
{
}
whereas a class method is defined with the STATIC keyword.
static public function bar()
{
}
In the instance method you can use $this to get access to the state of the instance on which the method was called. This is not available in the class method because it's not tied to any one instance. It can access other members of the class (provided they're not tied to an instance) with the self keyword though.
Instance methods are called as follows:
$a = new ObjType ()
$output = $a -> foo ();
Class methods are called as follows:
$output = ObjType::bar ();
https://stackoverflow.com/questions/8853419/calling-a-class-function-without-using-this-function-name-php
No comments:
Post a Comment