PHP 类和包含
我有以下问题:
这是我的主文件index.php
。
<?php
class myClass
{
function myClass()
{
echo '[constructor]';
$this->myVar = '[i am making a test]';
$this->A();
}
function A()
{
echo '[function A works too]';
echo $this->myVar;
}
}
$test = new myClass;
?>
现在我需要将function A
移动到另一个PHP文件includes/function_a.php
中,我可以在主文件中include_once。原因是为了让我的主文件更小并且更容易阅读。
完成此操作的最佳实践是什么,扩展?
编辑:
我已经使用扩展完成了此操作:
index.php
<?php
include_once('includes/function_a.php');
class myClass extends anotherClass
{
function myClass()
{
echo '[constructor]';
$this->myVar = '[i am making a test]';
$this->A();
}
}
$test = new myClass;
?>
includes/function_a.php
<?php
class anotherClass
{
function A()
{
echo '[function A works too]';
echo $this->myVar;
}
}
?>
有更好的想法吗?
I have the following question:
This is my main file index.php
.
<?php
class myClass
{
function myClass()
{
echo '[constructor]';
$this->myVar = '[i am making a test]';
$this->A();
}
function A()
{
echo '[function A works too]';
echo $this->myVar;
}
}
$test = new myClass;
?>
Now I need to move function A
into another PHP file includes/function_a.php
which I could include_once in the main file. The reason is to make my main file smaller and easier to read.
What is the best practice of having this done, EXTENDS?
EDIT:
I've done this using EXTENDS:
index.php
<?php
include_once('includes/function_a.php');
class myClass extends anotherClass
{
function myClass()
{
echo '[constructor]';
$this->myVar = '[i am making a test]';
$this->A();
}
}
$test = new myClass;
?>
includes/function_a.php
<?php
class anotherClass
{
function A()
{
echo '[function A works too]';
echo $this->myVar;
}
}
?>
Any better ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在问题末尾暗示了最好的方法。您需要创建一个父类并让您的“myClass”扩展您的父类。然后,“myClass”将继承父类的方法,并且父类可以位于另一个文件中。这就是您要找的吗?
You hint at the best way to do it at the end of your question. You would need to create a parent class and have your "myClass" extend your parent class. "myClass" would then inherit the methods of the parent class and the parent class could be in another file. Is that what you were looking for?
除非您想将
myClass
作为基类,否则不要使用另一个类EXTEND
它。包含包含
myClass
类的文件并实例化myClass
对象以使用函数A
。Unless you want to serve
myClass
as a base class do notEXTEND
it using another class.Include the file containing
myClass
class and instantiate an object ofmyClass
to use functionA
.如果函数太长,请将其拆分为更小的函数。它们必须有用,而不是像 functionA_part01...
例如。 getDataFromFile(),如果函数 A 读取文件。
如果仍然需要创建新文件,可以使用 myClass 在扩展中创建一个抽象类。
也许你应该重新考虑你的课程设计?
if a function is too long, split it in more small functions. they must be usefull, not like functionA_part01...
eg. getDataFromFile(), if Function A reads out of a file.
if there is still the need to create a new file, you can create an abstract-Class in extends them with myClass.
maybe you should rethink your class design?