PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 28, 2022

[FIXED] Declaring closure to class attribute in PHP

 February 28, 2022     closures, functional-programming, object, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing