[英]how to call the function of the same class inside another function of that class in php
[英]Call a class inside another class in PHP
嘿那里我想知道這是怎么做的,因為當我在類的函數內嘗試以下代碼時它會產生一些我無法捕獲的php錯誤
public $tasks;
$this->tasks = new tasks($this);
$this->tasks->test();
我不知道為什么類的啟動需要$ this作為參數:S
謝謝
class admin
{
function validate()
{
if(!$_SESSION['level']==7){
barMsg('YOU\'RE NOT ADMIN', 0);
return FALSE;
}else{
**public $tasks;** // The line causing the problem
$this->tasks = new tasks(); // Get rid of $this->
$this->tasks->test(); // Get rid of $this->
$this->showPanel();
}
}
}
class tasks
{
function test()
{
echo 'test';
}
}
$admin = new admin();
$admin->validate();
你不能在類的方法(函數)中聲明public $ tasks。如果你不需要在該方法之外使用tasks對象,你可以這樣做:
$tasks = new Tasks($this);
$tasks->test();
當您使用想要在整個班級中可用的變量時,您只需要使用“$ this->”。
你有兩個選擇:
class Foo
{
public $tasks;
function doStuff()
{
$this->tasks = new Tasks();
$this->tasks->test();
}
function doSomethingElse()
{
// you'd have to check that the method above ran and instantiated this
// and that $this->tasks is a tasks object
$this->tasks->blah();
}
}
要么
class Foo
{
function doStuff()
{
$tasks = new tasks();
$tasks->test();
}
}
用你的代碼:
class Admin
{
function validate()
{
// added this so it will execute
$_SESSION['level'] = 7;
if (! $_SESSION['level'] == 7) {
// barMsg('YOU\'RE NOT ADMIN', 0);
return FALSE;
} else {
$tasks = new Tasks();
$tasks->test();
$this->showPanel();
}
}
function showPanel()
{
// added this for test
}
}
class Tasks
{
function test()
{
echo 'test';
}
}
$admin = new Admin();
$admin->validate();
你遇到的問題是這行代碼:
public $tasks;
$this->tasks = new tasks();
$this->tasks->test();
$this->showPanel();
public
關鍵字用於類的定義,而不是類的方法。 在php中,你甚至不需要在類中聲明成員變量,你可以只做$this->tasks=new tasks()
並為你添加它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.