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.

1
  • yes it's possible. Doing this creates a closure. In fact this was one way to achieve OOP encapsulation before classdef-style objects were introduced Commented Jan 23, 2014 at 17:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.