Skip to content

Update TP: 45_static_method_from_variable #35

@felix-20

Description

@felix-20

Testability pattern

Pattern 45_static_method_from_variable

Problem statement

The original code:

<?php
  class A {
      public $one = 1;

      function __construct($b){
        $this->one = $b;
      }
    
      static function show_one() {
          echo $this->one;
      }
  }
  
$b = $_GET["p1"];
$a = new A($b);
$a::show_one();

When trying to run this code on my machine with PHP 8.1.2 and Zend Engine v4.1.2 it throws a Fatal error.
In my opinion that is correct. The instance code does not work, because $this is accessed in the static function show_one() which should not be possible as $this refers to a specific instance of a class, while the static function show_one() refers to the class itself.

Proposed changes

In my understanding, this pattern targets, that a static function can be called from an instance of the class.
If that is the right understanding, changing the variable $one from public to static should fix the problem.
The changed code could look like this:

<?php
  class A {
      static $one = 1;

      function __construct($b){
        self::$one = $b;
      }
    
      static function show_one() {
        return self::$one;
      }
  }
  
$b = $_GET["p1"]; // source
$a = new A($b);
$c = $a::show_one();
echo $c; // sink

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACK_WAITINGissue to be reviewed and confirmedUPDATE_TPissue is about updating a testability pattern

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions