-1

I have the following script:

<?php
class A {
    protected static $aliases = [];

    public static function doSomething()
    {
        foreach (self::$aliases as $column => $alias) {
           // do something
           echo "$column: $alias" . PHP_EOL;
        }
    }
}
class B extends A {
    protected static $aliases = [
        'id' => 'real_id',
        'name' => 'real_name',
    ];
}

$obj = B::doSomething(); // does nothing

How could I make B inherit the function but use it's own parameters? I have attempted to create a getInstance type function, however I don't think I understood the concept correctly and didn't work. I have since moved this function into a trait -- it still seems to give the same result.

Any and all assistance is appreciated.

Josh Murray
  • 619
  • 5
  • 18
  • Does this question answer your question? https://stackoverflow.com/questions/11710099/what-is-the-difference-between-selfbar-and-staticbar-in-php – HPierce Oct 27 '18 at 16:23

2 Answers2

2

You need to change self::$aliases to static::$aliases to refer to B's aliases within A.

See here: https://3v4l.org/h3dP4

<?php

class A {
    protected static $aliases = [];

    public static function doSomething()
    {
        foreach (static::$aliases as $column => $alias) {
           // do something
           echo "$column: $alias" . PHP_EOL;
        }
    }
}
class B extends A {
    protected static $aliases = [
        'id' => 'real_id',
        'name' => 'real_name',
    ];
}

$obj = B::doSomething();

This answer does a better job explaining why this works: What is the difference between self::$bar and static::$bar in PHP?

HPierce
  • 7,249
  • 7
  • 33
  • 49
0

Try using static to access the child property like this

public static function doSomething()
{
    foreach (static::$aliases as $column => $alias) {
       // do something
       echo "$column: $alias" . PHP_EOL;
    }
}

Take a look http://php.net/manual/en/language.oop5.late-static-bindings.php for better reference

Fil
  • 8,225
  • 14
  • 59
  • 85