Topic on Project:Support desk

How do I get the Name of any NameSpace by its number via PHP?

3
Summary last edited by Spas.Z.Spasov 16:57, 12 February 2020 4 years ago

It is much more complicated than I expected. The explanation provided by @Bawolff decries all possible cases very well.

Spas.Z.Spasov (talkcontribs)

I'm tring to find a way to get the translated name of the namespace MediaWiki (Nr. 8) via my PHP code - for example in Bulgarian it is translated to МедияУики.

I've fund so far that the constant NS_MEDIAWIKI contains the number of the namespace 8. Also the I've found the translated names are defined via the the array $namespaceNames. But echo $namespaceNames[NS_MEDIAWIKI] returns nothing.

I'm using the hooks ArticleViewHeader and BeforePageDisplay, but if it is not possible to get the namespace name via these hooks I would use another one.

Could someone give me a hand in this case?

Bawolff (talkcontribs)

You probably want either the getFormattedNsText or getNsText method of the language object.

It depends a bit what language you want it in. If you want to use the page language [e.g. what's stored in page_lang field in db, falling back to ContentHandler default, and then falling back to Content language], you might do something like $article->getTitle()->getPageLanguage()->getFormattedNsText( NS_MEDIAWIKI );. [Where $article would be the first argument to the ArticleViewHeader hook] If at all possible, this is probably the version you want. If page language isn't what language the page is actually written in, you probably want to fix that rather then use a different language object.

If you want to use the content language (Default language of the wiki): MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNsText( NS_MEDIAWIKI );

If you want the user language, use $article->getContext()->getLanguage()->getFormattedNsText( NS_MEDIAWIKI );. Be very careful with this version though, as if it gets cached you may have cache pollution issues where users get the wrong langauge.

If you want to do it for an arbitrary language (replacing 'bg' with the lang code): MediaWiki\MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'bg' )->getFormattedNsText( NS_MEDIAWIKI );

Spas.Z.Spasov (talkcontribs)

Thank you very much, @Bawolff, for the great answer!