'Declaring closure to class attribute in PHP

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 1:[1]

HI this can be done by using __call magic method it will byepass the fetal error The

__call method invoked when we try to access some undefined method, I think

it may helpful to you.......

class Totalizer {

public $count;

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

public function __call($method, $args)
{
    if ($method=="count") {

    } else {
        echo "Error ! method not foound!";
    }
}

}

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

Solution 2:[2]

This might be late, but since PHP 7, you can do this (parenthesis are important):

var_dump(($foo->count)(123));

Solution 3:[3]

<?php
    class Totalizer{

        public function __construct(){
        }

        public function product( $count ) {
            if( is_int( $count ) )
                return $count;
            else
                return false;
        }

    }

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pardeep
Solution 2 smknstd
Solution 3