Matlab class with knowledge of instance name in constructor

I would like to have a class that, in its constructor, can have knowledge (extract as string) the name of its instance.

For now, I have handled the extraction of the name 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 calls for an ugly

A = mysession;  A.build

      

to work ...

+2


source to share


1 answer


Unable to get the variable name that is used to assign the output of a function or class constructor. As you have found, the only way to get the name of an object variable in the call stage is to call another method on the class from which you can use inputname

to request it.



Aside, it is not clear why you need this, but I would strongly discourage. Particularly with classes, handle

you can have multiple variables pointing to the same object, so the object has multiple names.

+1


source







All Articles