简体   繁体   中英

Abstract Class Lambda Function in PHP

I am getting confused in the usage of abstract class lambda function usage in PHP returning bool value. I want to define a lambda function which takes in an obj type input and returns bool and this return value is stored in a variable. And I want to leave the implementation to the child classes. How to define this function? I am currently writing below which is giving me error:

$var = (function(OBJ type): bool);

?'input' => this::var

Here is example for better understanding.

<?php
abstract class AbstractClass {
    abstract public function getFunction(object $callback): bool;
}

class ChildClass extends AbstractClass {
    public bool $get_function_result;

    public function getFunction(object $callback): bool {
        $this->get_function_result = is_callable($callback);
        return $this->get_function_result;
    }
}

$instance = new ChildClass();
$result = $instance->getFunction(function () {});
var_dump($result);

You can read more about abstract classes here: https://www.php.net/manual/en/language.oop5.abstract.php

Update:

<?php
class JustClass {
    public object $example;
    function __construct() {
        $this->example = function(object $callback): bool {
            return true;
        };
    }
}
$instance = new JustClass;
echo ($instance->example)(function() {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM