[英]In php how do I call function from another class inside a different class?
[英]In PHP, how do I call master class functions to different pages?
我有整個項目的大師班。 我需要按如下所述將主類函數調用到不同的頁面和方法:
Master.php
class master{
function login_parser(){
}
}
Index.php
include('master.php')
function test(){
$obj = new master();
}
function test2(){
obj = new master();
}
我需要為每個方法調用對象。 有沒有辦法一次調用一個對象?
您可以將該對象作為函數的參數,因此也很明顯,該對象也有依賴關系,也可以進行類型提示(如果僅通過全局使用它就會丟失)
$obj = new master();
function test(master $obj) {
...
}
然后致電:
test($obj);
有很多方法可以實現這一目標
Tobias Zander提供了參數選項(依賴注入)
優點:知道功能需要什么
缺點:最終可能會給函數提供很多參數
$obj = new master();
function test(master $obj) {
...
}
第二種方法可能是使用全局變量
優點:沒有參數鏈
缺點:不知道該函數具有哪些依賴項
$obj = new master();
function test(){
global $obj; //Now carry on
}
第三種方式,單例
優點:面向對象的方式
缺點:不知道依賴項
在這種情況下,您的主類需要一個返回自身的靜態函數
class Master
{
protected static $master ;
public static function load()
{
if(!self::$master instanceof Master) {
self::$master = new Master();
}
return self::$master;
}
}
現在,我可以使用load函數在腳本中的每個位置使用master,並且只會啟動一次
function test()
{
$master = Master::load();
}
我個人使用方法1,而不是使用類Test {protected $ master;
public function __construct(Master $master)
{
$this->master = $master;
}
public function whoo()
{
// now I can use $this->master as the master class
}
}
是的,而不是每次都創建對象。 在全局范圍內的功能之外創建。
include('master.php')
$obj = new master();
function test(){
global $obj; //Now carry on
}
function test2(){
global $obj;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.