2

Is there a way to create a function handle to a nested function that includes the parent function in the function handle?

As an example, say I have:

function myP = myParent()

    myP.My_Method = myMethod;

    function myMethod()
        disp "hello world"
    end
end

In another file, I could call the method by doing something like:

myP = myParent();
myP.My_Method();

But, if I have another function that takes function handles as a parameter and then calls the function, how do I pass in the function handle to myMethod in this case, since this new function can't create a myParent variable.

horchler
  • 18,384
  • 4
  • 37
  • 73
Jomnipotent17
  • 451
  • 7
  • 23
  • yes it's possible. Doing this creates a [closure](https://en.wikipedia.org/wiki/Closure_%28computer_programming%29). In fact this was one way to achieve [OOP encapsulation](https://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) before `classdef`-style objects were introduced – Amro Jan 23 '14 at 17:42

1 Answers1

3

The following seems to work:

function myP = myParent()

    myP.My_Method = @myMethod;

    function myMethod()
        s=dbstack;
        fprintf('Hello from %s!\n',s(1).name);
    end
end

Running it as follows:

>> myP = myParent()
myP = 
    My_Method: @myParent/myMethod
>> feval(myP.My_Method)
Hello from myParent/myMethod!
>> myP.My_Method()
Hello from myParent/myMethod!

It is also fine to run it from another function:

% newfun.m
function newfun(hfun)
feval(hfun)

Test:

>> newfun(myP.My_Method)
Hello from myParent/myMethod!

Depending on what you are doing, this should be enough. Note that each handle you create is unique since it contains information about externally scoped variables (variables pulled in the parent):

When you create a function handle for a nested function, that handle stores not only the name of the function, but also the values of externally scoped variables.

chappjc
  • 30,359
  • 6
  • 75
  • 132
  • Sorry, I forgot to put the @myMethod in my original code. I have that. What I really want to do is be able to create a function handler to the My_Method call. Any ideas? – Jomnipotent17 Jan 23 '14 at 05:13
  • You do get a function handle, but you have to get first via `myParent`, as an output argument. The output variable `myP` is not an instance of `myParent`, just a struct containing the function handle you need. – chappjc Jan 23 '14 at 05:14