Reputation: 525
I would like to have a class which, in its constructor, can have knowledge (extract as a string) its instance name.
For the moment I worked the name extraction out like this:
classdef mysession
methods (Access = public)
function this=mysession (varargin)
this.cargs=varargin;
this.built=false;
end
function id=build(this)
id=this.mynameis;
this.id = id;
%% instructions needing id
built=true;
end
function name = mynameis (this)
name=evalin ('caller', 'inputname');
end
end
properties (Access=private)
id
built
cargs
end
end
which requires the ugly
A = mysession; A.build
syntax in order to work...
Upvotes: 2
Views: 460
Reputation: 65430
There is no way to get the variable name that is used to assign the output of a function or class constructor. As you've discovered, the only way to get the object's variable name in the calling workspace is to call another method of the class at which point you can use inputname
to query it.
That aside, it's not clear why you need to do this but I'd strongly discourage it. Particularly with handle
classes, you can have multiple variables point to the same object, therefore the object technically has multiple names.
Upvotes: 1