这是我的班级代码:
class myClass
{
public function myFunc()
{
$myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
我用这个:
$nCls = new myClass;
$nCls->result();
要显示Test str
表单myFunc()
但未显示任何内容。我认为问题是:
echo myClass::myFunc()->$myvar;
感谢您的帮助。
答案 0 :(得分:2)
你混合了很多概念。
首先,您必须创建类myClass
的新对象:
$nCls = new myClass();
然后,您可以在该类上调用成员函数(方法):
$nCls->result();
在result()
中,您只需使用$this
调用另一种方法:
public function result()
{
echo $this->myFunc();
}
请注意,这没有任何作用。变量$myvar
是本地的,而不是类属性。我建议您阅读object oriented programming,特别是object oriented PHP。
答案 1 :(得分:2)
class myClass {
public $myvar;
public function myFunc() {
$this->myvar = 'Test str';
return $this;
}
public function result() {
echo $this->myFunc()->myvar;
}
}
$nCls = new myClass;
$nCls->result();
你可以这样做,但这不是一个好习惯。
答案 2 :(得分:1)
问题是作用域,你不能在另一个函数中调用一个变量,为类定义一个属性并从函数中设置它然后用result()
检索属性:
class myClass
{
public $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo $this->myvar;
}
}
答案 3 :(得分:1)
问题是您在方法$myvar
的范围内仅声明myFunc()
。这意味着它在该方法之外是不可见的。将其声明为类成员:
class myClass
{
private $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
答案 4 :(得分:1)
include "views.php";
class Controller extends views{
function index(){
$this->head();
$this->home();
}
function privacy(){
$this->head();
$this->privc();
}
function about(){
$this->head();
$this->abt();
}
function address(){
$this->head();
$this->add();
}
}
$obj=new Controller();
if(isset($_GET['fun'])){
$obj->$_GET['fun']();
}
else{
$obj->index();
}
This is views.php code
class views{
function head(){
include "views/header.php";
echo "<br>this is header";
}
function abt(){
include "views/about.php";
echo "<br>This is about us page";
}
function home(){
include "views/home.php";
echo "<br>This is Home page";
}
function privc(){
include "views/privacy.php";
echo "<br>This is privacy page";
}
function add(){
include "views/address.php";
echo "<br>This is address page";
}
}