[英]How do I Instantiate a class within a class in .php
I'm new to OOP and I can't figure out why this isn't working.我是 OOP 的新手,我不明白为什么这不起作用。 Is it not ok to instantiate a class with in a class.
在一个类中实例化一个类是否可以。 I've tried this with included file with in the method and it didn't make a change.
我已经在方法中使用包含的文件尝试过这个,但它没有做任何改变。
include('Activate.php');
class First {
function __construct() {
$this->activate();
}
private function activate() {
$go = new Activate('Approved');
}
}
$run = new First();
Are you saying that you want to access $go
?您是说要访问
$go
吗? because, if that is the case, you need to change the scope of it.因为,如果是这种情况,您需要更改它的范围。
As you see, $go
in this method is only available inside activate()
:如您所见,此方法中的
$go
仅在activate()
可用:
private function activate() {
$go = new Activate('Approved');
}
to make it reachable from other location within the class, you would need to declare it outside activate()
:要使其可从类中的其他位置访问,您需要在
activate()
之外声明它:
private $go = null;
you call $go
by using $this
:你使用
$this
调用$go
:
private function activate() {
$this->go = new Activate('Approved');
}
After that, if you want to access go from outside class, you would need to create wrapper:之后,如果要从外部类访问 go,则需要创建包装器:
public function getGo(){
return $this->go;
}
Hope this helped.希望这有帮助。 Also, you can read the documentation about OOP in PHP .
此外,您可以阅读有关 PHP 中 OOP的文档。
Okay I figured out my issue.好的,我想出了我的问题。 My code had two errors.
我的代码有两个错误。 One that being my method was set to private and secondly I had an error in my
$parms
that I was sending to the class.一个作为我的方法被设置为私有,其次我在发送给班级的
$parms
中有一个错误。
include('Activate.php');
class First {
function __construct() {
$this->activate();
}
private function activate() {
$go = new Activate('Approved');
}
}
$run = new First();
You can access your private method with the help of create another public function in the same class and call the private function in the public method or function.您可以借助在同一类中创建另一个公共函数并在公共方法或函数中调用私有函数来访问私有方法。 Now you can call your private function with the help of $run instance.
现在您可以在$run实例的帮助下调用您的私有函数。
For example:例如:
class Cars{类汽车{
function getting(){
echo ("Hello World");
}
private function getting2(){
echo ("Hello World Againg");
}
public function getting3(){
$this->getting2();
}
} }
$class_object=new Cars; $class_object=新车;
print($class_object->getting3());打印($class_object->getting3());
Your output screen like the below image.您的输出屏幕如下图所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.