本文介紹了在php中沒有對象實例化的情況下調用類方法(帶構造函數)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我已經查看并嘗試過,但我找不到答案.
Ive looked and tried but I can't find an answer.
在 PHP 中,是否可以在不將其實例化為對象的情況下調用類的成員函數(當該類需要構造函數來接收參數時)?
In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object?
代碼示例(給出錯誤):
A code example (which gives errors):
<?php
class Test {
private $end="";
function __construct($value) {
$this->end=$value;
}
public function alert($value) {
echo $value." ".$this->end;
}
}
//this works:
$example=new Test("world");
$example->alert("hello");
//this does not work:
echo Test("world")::alert("hello");
?>
推薦答案
不幸的是 PHP 不支持這樣做,但你是一個有創造力和外觀的人 :D
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D
您可以使用工廠",示例:
You can use an "factory", sample:
<?php
class Foo
{
private $__aaa = null;
public function __construct($aaa)
{
$this->__aaa = $aaa;
}
public static function factory($aaa)
{
return new Foo($aaa);
}
public function doX()
{
return $this->__aaa * 2;
}
}
Foo::factory(10)->doX(); // outputs 20
這篇關于在php中沒有對象實例化的情況下調用類方法(帶構造函數)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!