Asked  10 Months ago    Answers:  5   Viewed   15 times

In PHP you can call a class's static method from an object instance (which is contained in an array) like this:

$myArray['instanceOfMyClass']::staticMethod(); // works

But for some reason when I use the $this variable, I get a parsing error. E.g:

$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR

Just to illustrate what I mean:

class MyClass{
    public static function staticMethod(){ echo "staticMethod calledn"; }
}

$myArray = array();
$myArray['instanceOfMyClass'] = new MyClass;
$myArray['instanceOfMyClass']::staticMethod(); // works

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;
        $this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
    }
}

new RunCode;

Any ideas on how to get around this?

 Answers

4

You actually can use "->" to call static method:

$this->myArray['instanceOfMyClass']->staticMethod();
Sunday, August 15, 2021
 
2

You can do

function unsetValue(array $array, $value, $strict = TRUE)
{
    if(($key = array_search($value, $array, $strict)) !== FALSE) {
        unset($array[$key]);
    }
    return $array;
}

You can also use spl_object_hash to create a hash for the objects and use that as array key.

However, PHP also has a native Data Structure for Object collections with SplObjectStorage:

$a = new StdClass; $a->id = 1;
$b = new StdClass; $b->id = 2;
$c = new StdClass; $c->id = 3;

$storage = new SplObjectStorage;
$storage->attach($a);
$storage->attach($b);
$storage->attach($c);
echo $storage->count(); // 3

// trying to attach same object again
$storage->attach($c);
echo $storage->count(); // still 3

var_dump( $storage->contains($b) ); // TRUE
$storage->detach($b);
var_dump( $storage->contains($b) ); // FALSE

SplObjectStorage is Traversable, so you can foreach over it as well.

On a sidenote, PHP also has native interfaces for Subject and Observer.

Thursday, April 1, 2021
 
Sabya
 
2
  • Yes, you can call a trait static method [implemented by types] from another trait static method [implemented in the trait].
  • Static methods are always called on a trait like SomeTrait::some_method().
  • Where there is no Self or self in [a trait] function signature, it is not callable at present. The standard workaround until UFCS comes is to take an argument _: Option<Self> and pass it None::<T>.

See original question for code that (as of today) compiles.

Saturday, August 14, 2021
 
5
function benchmark($func_name, $iterations) {
    $begin = microtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $func_name();
    }
    $end = microtime(true);

    $execution_time = $end - $begin;

    echo $func_name , ': ' , $execution_time;
}

function standClass() {
    $obj = new stdClass();
    $obj->param_one = 1;
    $obj->param_two = 2;
}

function castFromArray() {
    $obj = (object)array('param_one' => 1, 'param_two' => 2);
}


benchmark('standClass', 1000);
benchmark('castFromArray', 1000);

benchmark('standClass', 100000);
benchmark('castFromArray', 100000);

Outputs:

standClass: 0.0045979022979736
castFromArray: 0.0053138732910156

standClass: 0.27266097068787
castFromArray: 0.20209217071533

Casting from an array to stdClass on the fly is around 30% more efficient, but the difference is still negligible until you know you will be performing the operation 100,000 times (and even then, you're only looking at a tenth of a second, at least on my machine).

So, in short, it doesn't really matter the vast majority of the time, but if it does, define the array in a single command and then type-cast it to an object. I definitely wouldn't spend time worrying about it unless you've identified the code in question as a bottleneck (and even then, focus on reducing your number of iterations if possible).

Saturday, August 21, 2021
3

You need to create the object of the class to call non class methods, You need an instance to call such methods that is why those methods are called instance methods.

calling [self instanceMethod] from class method wont work, because self in class method points to the class rather any instance. Here you can find information the on use of self in class methods.

Wednesday, January 5, 2022
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :