简体   繁体   English

仅当类在php中实例化时,我才能要求类函数吗?

[英]Can I require class-functions only if the class is instantiated in php?

Trying to improve my code's agility and loading time, I thought of doing this, so that the functions would be required only if the class was instantiated. 为了提高代码的敏捷性和加载时间,我想到了这样做,以便仅在实例化该类时才需要使用这些函数。

class User
{
    public function __construct()
    {
       require('all_user_fns.php');
    }
}

Inside all_user_fns.php will reside all User class's functions. all_user_fns.php内部将驻留所有User类的函数。

Is that feasible (maybe in another way)? 那可行吗(也许是另一种方式)? Does it have any advantages when it comes to speed? 在速度方面有什么优势吗?

To be honest this will be slower (you're having to do an additional include after all) although meaninglessly so. 老实说,这会比较慢(毕竟您必须做一个额外的include),尽管毫无意义。 As such, if speed is really an issue look at one of the opcode caches such as the Alternative PHP Cache (APC) 因此,如果速度确实是一个问题,请查看操作码缓存之一,例如备用PHP缓存 (APC)

Somewhat more concerning, it's going to make maintaining the code painful and will quite possibly cause issues when attempting to use visibility keywords such as private/protected/public depending on what IDE you're using. 更令人担忧的是,这将使代码维护很痛苦,并且在尝试使用可见性关键字(例如,取决于所使用的IDE的私有/受保护/公共)时,很可能会引起问题。

If those functions exist just to modify and interact with user objects they they should be member functions of that class. 如果存在这些功能只是为了修改用户对象并与用户对象进行交互,则它们应该是该类的成员函数。 That's the point of objects, to encapsulate and organize related functionality. 这就是对象的目的,以封装和组织相关功能。

My guess: Won't have any noticeable impact on speed. 我的猜测:对速度不会有任何明显的影响。 Plus it makes your code harder to understand and maintain. 另外,它使您的代码更难以理解和维护。 I'd steer clear and look for other ways to speed things up. 我会避开并寻找其他加快速度的方法。

I'd suggest moving the user functions to the User class itself as methods - it makes more sense and is more easily maintained. 我建议将用户函数作为方法移至User类本身-更加有意义并且更易于维护。 If you think maintenance is not an issue, let me know in 6 months and tell me how did that work you for you :) 如果您认为维护不是问题,请在6个月内告知我,并告诉我这对您有何帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM