|On this page…|
See Packages Create Namespaces for information about packages.
You can import classes into a function to simplify access to class members. For example, suppose there is a package that contains a number of classes, but you need to use only one of these classes in your function, or perhaps even just a static method from that class. You can use the import command as follows:
function myFunc import pkg.cls1 obj = cls1(arg,...); % call cls1 constructor obj.Prop = cls1.StaticMethod(arg,...); % call cls1 static method end
Note that you do not need to reference the package name (pkg) once you have imported the class (cls1). You can also import all classes in a package using the syntax pkg.*, where * indicates all classes in the package. For example,
function myFunc import pkg.* obj1 = cls1(arg,...); % call pkg.cls1 constructor obj2 = cls2(arg,...); % call pkg.cls2 constructor a = pkgFunction(); % call package function named pkgFunction end
You can use import with package functions:
function myFunc import pkg.pkfcn pkfcn(arg,...); % call imported package function end
Suppose you have the following folder organization:
+pkg/timedata.m % package function +pkg/@myclass/myclass.m % class definition file +pkg/@myclass/timedata.m % class method
Now import the package and call timedata on an instance of myclass:
import pkg.* myobj = pkg.myclass; timedata(myobj)
A call to timedata finds the package function, not the class method because MATLAB® applies the import and finds pkg.timedata first. Do not use a package in cases where you have name conflicts and plan to import the package.
You can not clear the import list from a function workspace. To clear the base workspace only, use: