1

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

Julio Marins
  • 10,039
  • 8
  • 48
  • 54

4 Answers4

1

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
        }
    }
}
Community
  • 1
  • 1
Lee Saferite
  • 3,124
  • 22
  • 30
0

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));

pardeep
  • 21
  • 3
0

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

var_dump(($foo->count)(123));
smknstd
  • 341
  • 1
  • 3
  • 6
-2
<?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));
Alex
  • 478
  • 2
  • 11