How to begin?
This is step-by-step guide to starting a C# to PHP translation.
1. Start new Visual Studio Project
Create new project in Visual Studio. In option window choose „.NET Framework 4.5” platform and „.NET Library” project type.
2. Add Lang.Php reference
Lang.Php library is available on nuget so you can install it using „Package Manager Console” (menu Tools => Library Package Manager => Package Manager Console) . Type
1 |
install-package Lang.Php |
3. Prepare sample C# code
Rename Class1.cs into IndexPage.cs and modify code:
3.1 Add Lang.Php to using list
Add following line to using list
1 |
using Lang.Php; |
This lets you easy access to Lang.Php namespace.
3.2 Derive your class from PhpDummy
Derive your class from Lang.Php.PhpDummy base class. This is C# wrapper around well-known PHP functions like echo, htmlspecialchars, number_format and many more. Methods declared in PhpDummy class are as similar to their PHP sisters as possible so if you have PHP programming experience you will feel like in your home.
3.3 Decorate class with PageAttribute
Decorate your class using PageAttribute with „index” as parameter
1 |
[Page("index")] |
Class decorated with PageAttribute will be converted as normal class. One extra action is performed: Invocation of static method „PhpMain” is appended to php output file (see next point). Attribute parameter lets you to specify php file name, „index.php” in this case.
3.4 Create PhpMain method
Cs2php compiler expects that class decorated with PageAttribute also contains static method „PhpMain”. This method is PHP page starting point.
Add method with following code
1 2 3 4 |
public static void PhpMain() { echo("Hello C# to PHP world."); } |
Your class should looks like this:
4. Compile code
You have do download and build cs2php compiler by yourself. Source code is available on GitHub. Binary version is currently not distributed due to Microsoft Rosylin licence limitations. See FAQ for details.
cs2php
is command line util so open MS Windows console and run compiler with 2 parameters
- path to Visual Studio project
- output folder
Assume we’re in project folder type
1 |
c:\cs2php\cs2php.exe MyFirstPhpCode.csproj c:\cs2php\output\MyFirstPhpCode\ |
c:\cs2php\cs2php.exe is full path to compiler. Change if it is located in other location. Compare compiler messages with following:
Go into output folder (c:\cs2php\output\MyFirstPhpCode\
in the example) . You should find „index.php
” file with following code.
Congratulations ! Think C#, make PHP.