Monday, February 28, 2022

[FIXED] Declaring closure to class attribute in PHP

Issue

Its strange, i can do

<?php

    $foo = function($a){
        return $a;
    };

var_dump($foo(123));

But in the scope of a classe if a do:

<?php

    class Totalizer{

        public $count;

        public function __construct(){
            $this->count = function($product){
                return  $product;
            };
        }

    }

    $foo = new Totalizer;
    var_dump($foo->count(123));

Fatal error: Call to undefined method Totalizer::count()

My question is how can i do the same as the first snippet but in class scope?

ps: PHP 5.5


Solution

PHP Currently doesn't allow directly calling a function stored as an object property.

It allows properties and methods of an object to have the same name actually.

One suggested solution to this issue is from another, almost identical question

class Totalizer
{
    public $count;

    public function __construct()
    {
        $this->count = function ($product) {
            return  $product;
        };
    }

    public function __call($method, $args)
    {
        if (is_callable(array($this, $method))) {
            return call_user_func_array($this->$method, $args);
        } else {
            // else throw exception
        }
    }
}


Answered By - Lee Saferite

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.