php基础不好,基础不好,问个php类调用的初级问题
new 出來(lái)的對(duì)象沒辦法直接返回字符串,返回的都是對(duì)象;
我大概明白你的意思,你就是想new 的時(shí)候直接返回結(jié)果了,就少些那個(gè)do_php(),可以用靜態(tài)的方式
方案一:
class Test
{
private $name;
private $age;
private $work;
static function g($name, $age, $work)
{
return new Test($name, $age, $work);
}
public function __construct($name,$age,$work){
$this->name=$name;
$this->age=$age;
$this->work=$work;
}
public function do_php()
{
$content = "我的名字是" . $this->name . ",已經(jīng)" . $this->age . "歲了,現(xiàn)在的工作是" . $this->work;
return $content;
}
}
$c = Test::g('張三',42,'程序猿')->do_php();
echo $c;
方案2
class Test
{
private $name;
private $age;
private $work;
static function g($name, $age, $work)
{
$instance = new Test($name, $age, $work);
return $instance->do_php();
}
public function __construct($name,$age,$work){
$this->name=$name;
$this->age=$age;
$this->work=$work;
}
public function do_php()
{
$content = "我的名字是" . $this->name . ",已經(jīng)" . $this->age . "歲了,現(xiàn)在的工作是" . $this->work;
return $content;
}
}
$c = Test::g('張三',42,'程序猿');
echo $c;
望采納
備注:重復(fù)調(diào)用Test類會(huì)實(shí)例化很多對(duì)象在內(nèi)存中,如果需要優(yōu)化,請(qǐng)優(yōu)化g方法
static function g($name, $age, $work)
{
static $instance;
if (!isset($instance)) {
$instance = new Test($name, $age, $work);
}
return $instance;
}
總結(jié)
以上是生活随笔為你收集整理的php基础不好,基础不好,问个php类调用的初级问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: elasticsearch索引创建cre
- 下一篇: win10内存优化方法有哪些