An entirely OO solution to add dynamicly methods to classes, I used in a project:
class ProductPart {
protected $data;
protected $plugins = array[];
function __construct[$data]{
$this->data = $data;
}
public function register[ProductPlugin $plugin]{
if[!in_array[$plugin, $this->plugins]]{
$this->plugins[$plugin->toString[]] = $plugin;
} else {
throw new Exception['Function allready defined'];
}
}
public function unregister[ProductPlugin $plugin]{
if[isset[$this->plugins[$plugin->toString[]]]]{
unset[$this->plugins[$plugin->toString[]]];
} else {
throw new Exception['No such function'];
}
________số 8_______
protected function __call[$method, $args] {
if[isset[$this->plugins[$method]]]{
array_unshift[&$args, $this->data];
array_unshift[&$args, $this];
return $this->plugins[$method]->run[$args[0], $args[1], $args[2]];
} else {
throw new Exception['No such function'];
}
}
} ?>
I simplified the class somewhat for clearity.
protected $data;
0
protected $plugins = array[];
function __construct[$data]{
protected $data;
1
protected $plugins = array[];
function __construct[$data]{
protected $data;
2
protected $plugins = array[];
function __construct[$data]{
protected $data;
3
protected $plugins = array[];
function __construct[$data]{
protected $data;
4
protected $plugins = array[];
function __construct[$data]{
protected $data;
5
protected $plugins = array[];
function __construct[$data]{
protected $data;
6
protected $plugins = array[];
function __construct[$data]{
protected $data;
7
protected $plugins = array[];
function __construct[$data]{
protected $data;
8
protected $plugins = array[];
function __construct[$data]{
protected $data;
9
protected $plugins = array[];
function __construct[$data]{
protected $data;
7
protected $plugins = array[];
function __construct[$data]{
class A
{
const NAME = 'A';
public static function test[] {
$args = func_get_args[];
echo static::NAME, " ".join[',', $args]." \n";
}
}
class B extends A
{
const NAME = 'B';
public static function test[] {
echo self::NAME, "\n";
forward_static_call[array['A', 'test'], 'more', 'args'];
forward_static_call[ 'test', 'other', 'args'];
}
}
B::test['foo'];
function test[] {
$args = func_get_args[];
echo "C ".join[',', $args]." \n";
}
?>
Để gọi một hàm từ một tệp khác trong PHP, bạn cần nhập tệp nơi hàm được xác định trước khi gọi nó
Bạn có thể nhập tệp PHP bằng cách sử dụng câu lệnh require
Ví dụ: giả sử bạn có một tệp có tên library.php
với nội dung sau
// library.php
function greetings[] {
echo "Hello World!";
}
Để gọi hàm greetings[]
từ tệp khác, bạn cần nhập tệp library.php
như hình bên dưới
// 👇 import the PHP file
require "library.php";
// 👇 call the function
greetings[];
Bằng cách sử dụng câu lệnh require
, PHP sẽ đánh giá mã trong tệp đó trước khi chạy tệp hiện tại