代码之家  ›  专栏  ›  技术社区  ›  emma

PHP拥有一个类,然后在同一个文件中使用它是不是一个坏习惯?[关闭]

  •  0
  • emma  · 技术社区  · 7 年前

    有没有不好的习惯 class php 文件中要有一小段代码来使用该类?例如:

    <?php
    
    class Class{
        //some code here
    }
    
    $class = new Class();
    //do something with it
    

    谢谢您!

    1 回复  |  直到 7 年前
        1
  •  4
  •   jfadich    7 年前

    一般认为这是不好的做法。它限制了类的可重用性。最好在自己的文件中包含类定义,然后在使用该类的任何地方包含该文件。包含类(或函数)定义的文件应该没有副作用。

    例如,您可能有一个名为 SomeClass.php 看起来像这样

    <?php
    
    class SomeClass {
        // code here
    }
    

    然后进入 index.php 您可以包含该文件并使用类

    <?php
    
    include "SomeClass.php";
    
    $class = new SomeClass('some data');
    $class->someMethod();
    

    在里面 anotherfile.php

    <?php
    
    include "SomeClass.php";
    
    $differentInstance = new SomeClass('different data');
    $differentInstance->someMethod();
    

    PHP Standards Recommendations (PSR) 是一组由社区管理的PHP指南,我建议您通读这些指南,以获得有关此类问题的更详细信息。明确地 PSR-1 Basic Coding Standard PSR-2 Coding Style Guide .