[英]Call a class inside another class in 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 嘿那里我想知道这是怎么做的,因为当我在类的函数内尝试以下代码时它会产生一些我无法捕获的php错误
public $tasks;
$this->tasks = new tasks($this);
$this->tasks->test();
I don't know why the initiation of the class requires $this as a parameter either :S 我不知道为什么类的启动需要$ this作为参数:S
thanks 谢谢
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: 你不能在类的方法(函数)中声明public $ tasks。如果你不需要在该方法之外使用tasks对象,你可以这样做:
$tasks = new Tasks($this);
$tasks->test();
You only need to use the "$this->" when your using a variable that you want to be available throughout the class. 当您使用想要在整个班级中可用的变量时,您只需要使用“$ this->”。
Your two options: 你有两个选择:
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();
}
}
or 要么
class Foo
{
function doStuff()
{
$tasks = new tasks();
$tasks->test();
}
}
with your code: 用你的代码:
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();
You're problem is with this line of code: 你遇到的问题是这行代码:
public $tasks;
$this->tasks = new tasks();
$this->tasks->test();
$this->showPanel();
The public
keyword is used in the definition of the class, not in a method of the class. public
关键字用于类的定义,而不是类的方法。 In php, you don't even need to declare the member variable in the class, you can just do $this->tasks=new tasks()
and it gets added for you. 在php中,你甚至不需要在类中声明成员变量,你可以只做$this->tasks=new tasks()
并为你添加它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.