在PHP中的另一个类中调用一个类 [英] Call a class inside another class in PHP
本文介绍了在PHP中的另一个类中调用一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我想知道如何做这样做,当我尝试下面的代码在一个类的函数中,它产生一些我不能捕获的PHP错误
Hey there I'm wondering how this is done as when I try the following code inside a function of a class it produces some php error which I can't catch
public $tasks;
$this->tasks = new tasks($this);
$this->tasks->test();
我不知道为什么类的启动需要$ this作为参数:S
I don't know why the initiation of the class requires $this as a parameter either :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();
推荐答案
类的方法(函数。)如果你不需要使用该方法之外的任务对象,你可以这样做:
You can't declare the public $tasks inside your class's method (function.) If you don't need to use the tasks object outside of that method, you can just do:
$tasks = new Tasks($this);
$tasks->test();
当你使用一个变量时,你只需要使用$ this->可在整个课程。
You only need to use the "$this->" when your using a variable that you want to be available throughout the class.
您的两个选项:
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();
这篇关于在PHP中的另一个类中调用一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文