public 在 php 中构造的访问函数

Access function from public construct in php

我有一个 php 程序,其中有一个函数和一个带有 public 构造函数的 class,我需要从 [=23] 内部调用该函数=] 构造如下代码:

class test {

    public $var0 = null;

    public function __construct() {

        $this->var0 = Tfunction('lol');

    }

}

function Tfunction ($String) {

    $S = ($String . ' !');

    return $S;

}

$j = new test();

echo($j);

当我 运行 它没有 运行 函数时,我尝试了一切但它不想将 'lol !' 放入我的 public 变量中,怎么可能我让这个工作?

需要注意的一件事我没有收到任何错误告诉我 class 无法访问 fontion 或类似的东西,似乎该行被忽略了并且 $var0 被归档为 null。

你的代码有几个问题,请参考文档:

错误:

  1. classtest()必须是classtest
  2. $this = Tfunction('lol');必须是 echo Tfunction('lol'); $this 必须从未分配。

固定码为:

Class test{

    public $var0 = null;

    public function __Construct() {

       echo Tfunction('lol');

    }

}

function Tfunction ($String) {

    $S = ($String . ' !');

    return $S;

}

$a = new test();

Class 声明错误。您需要创建 class

的对象
<?php   
class test {

    public $var0 = null;

    public function __Construct() {
   echo Tfunction('lol');



    }

}

$obj=new test();

function Tfunction ($String) {

    $S = ($String . ' !!');
    return $S;


}
?>

我运行你的代码输出的错误是;

'Object of class test could not be converted to string'

有两种方法可以解决这个问题,您可以使用其中一种;

  1. 将行 echo($j); 改为 echo($j->var0);

现在不是尝试打印对象,而是打印构造函数中设置的对象的 public 变量。

  1. 向您的对象添加一个 __toString() 方法,并使用它来输出 var0 字段。

    class test {
    
      public $var0 = null;
    
      public function __construct() {
    
        $this->var0 = Tfunction('lol');
    
      }
    
      public function __toString(){
    
        return $this->var0;
    
      }
    
    }
    
    function Tfunction ($String) {
    
      $S = ($String . ' !');
    
      return $S;
    
    }
    
    $j = new test();
    
    echo($j);
    

现在,当您尝试使用 echo($j); 打印对象时,它将使用您指定的 __toString() 来输出您的变量。

这两个修复意味着 'lol!' 已按预期输出到我的浏览器 window。