Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2007

Functions and variables should not be defined outside of classes

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Move this [function|variable] into a class.
    • Default Severity:
      Blocker
    • Impact:
      High
    • Likelihood:
      High
    • Legacy Key:
      VariableInPackageSpecificationCheck
    • Covered Languages:
      PHP, PL/SQL, Swift
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min

      Description

      Defining and using global variables and global functions, when the convention dictates OOP can be confusing and difficult to use properly for multiple reasons:

      • You run the risk of name clashes.
      • Global functions must be stateless, or they can cause difficult-to-track bugs.
      • Global variables can be updated from anywhere and may no longer hold the value you expect.
      • It is difficult to properly test classes that use global functions.

      Instead of being declared globally, such variables and functions should be moved into a class, potentially marked static, so they can be used without a class instance.

      This rule checks that only object-oriented programming is used and that no functions or procedures are declared outside of a class.

      Noncompliant Code Example

      <?php
      
      $name = "Bob"; // Noncompliant
      
      function doSomething($arg) {   // Noncompliant
        //...
      }
      
      class MyClass {
          //...
      }
      

      Compliant Solution

      <?php 
      class MyClass {
      
        public static $name = "Bob"; // Compliant
      
        public static function doSomething($arg) {              // Compliant
          //...
        }
        //...
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated: