For foreigners in Germany different legal regulations apply according to their country of origin. In the following, you can get an overview of the most important legal basis.
For all citizens from EU-member countries, the regulations of the Freedom of Movement Act/ EU apply which i.a. exempts them from the visa obligation when entering another EU-member country.
For all citizens from non-EU-countries, so-called "third-party countries", the regulations of the Residence Act apply which include an extensive visa obligation as well as provisions for the issue of a residence permit for staying in Germany.
For the stay of a foreigner from a third-party country in Germany for the purposes of study and work, particularly Section 16 (PhD-students) and Section 18 of the Residence Act (scientific staff members, guest researchers) are of special interest. In case of taking up an employment in Germany, also the Employment Regulation should be reconsidered, with regard to the university particularly §5 of the Regulation concerning "Science, Research and Development". An overview of the different residence permits for researchers can be downloaded here.
These indications should serve as first general orientation. With regard to the respective individual circumstances of each stay as a foreigner in Germany and the corresponding legal regulations, particularly when coming from a "third-party country", it is strongly recommended to get in touch with the responsible Immigration Authority as soon as possible in any case.