drngnh708353
2017-02-07 10:38 阅读 70
已采纳

什么是使用ini_set()的PSR-1兼容替代方案?

I am in the process of making my code base PSR-2 compliant (and therefore PSR-1 compliant) and I have come across the following code:

public function init()
{
    parent::init();

    // Allow A Larger PHP Memory Limit For This Script
    ini_set("memory_limit", "512M");

    // Allow A Larger Script Execution Limit For This Script
    ini_set('max_execution_time', 300);
}

Which is used to increase the amount of memory and execution time which this particular script (which is only accessible to site admin and run infrequently) is able to consume.

Setting the default memory_limit and max_execution_time in php.ini (which will be honoured by all standard scripts/files) and then increasing those limits as and when needed, certainly feels like a perfectly acceptable and logical implementation to me.

However, I remember that PSR-1 states that:

"Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both."

It then goes on to state that using ini_set() is an example of a side-effect (at least their example shows it being used outside the scope of a class or function):

<?php
// side effect: change ini settings
ini_set('error_reporting', E_ALL);

This documentation can be seen here

My questions are therefore:

  1. Is the use of ini_set() within a classes method (as per my context) an example of a side-effect?
  2. If so, what is the PSR-1 compliant alternative?

This particular script needs to be allowed greater memory usage and execution time, but I do not want to just increase the global php.ini settings for this as that would allow for all other PHP processes to use more memory and execution time that they should.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doujionggan9570 doujionggan9570 2017-02-07 10:46

    PSR-1 is just talking about the top-level code in the file. That top-level code should either be causing side effects or declaring things.

    In your example, you're defining a class and its methods. The side effect doesn't happen when loading the file, it happens when you call the function. To be PSR-1 compliant, that call should not be in the top-level code of this file.

    点赞 评论 复制链接分享

相关推荐