Using PHP library from C#
Requires nightly build from October 8, 2006 or later.
If you have a bunch of working PHP code forming a library you use in your PHP applications and would like to use it in C# applications as well, you’ll find this tutorial useful.
First, paste the following code into file called Library.php in some directory.
<? include "ClassC.php"; function f() { echo "Hello!\n"; } echo "Library initialized: Now, you can use ". "classes and functions declared here.\n"; ?>
Than paste the following class in file named ClassC.php in the same directory:
<? class C { public $array = array(1,2,3); function __construct($data) { $this->data = $data; } } ?>
To build the class library using Phalanger use following command:
phpc /target:dll /out:ClassLibrary.dll Library.php ClassC.php
This command builds the two scripts into an assembly called ClassLibrary. Let’s create a C# and VB.NET console applications now that reference this library and call a function declared in Library.php and creates an instance of a class declared in ClassC.php.
In C#, the program using the library may look like following:
using PHP.Core; using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { ScriptContext context = ScriptContext.CurrentContext; // redirect PHP output to the console: context.Output = Console.Out; // get a representative type of the ClassLibrary library: Type library_representative = typeof(ClassLibrary); // include the Library.php script, which initializes the // whole library (it is also possible to include more // scripts if necessary by repeating this call with various // relative script paths): context.IncludeScript("Library.php", library_representative); // call function f(): context.Call("f"); // create an instance of type C, passes array // ("a" => 1, "b" => 2) as an argument to the C's ctor: object c = context.NewObject("C", PhpArray.Keyed("a", 1, "b", 2)); // var_dump the object: PhpVariable.Dump(c); } } }
You can use Visual Studio to build the C# program, or if you prefer command line compiler just run the following:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /reference:"C:\Program Files\Phalanger v2.0\PhpNetCore.dll" /reference:"ClassLibrary.dll" /out:ConsoleApplication.exe /target:exe Program.cs
And that’s it
! If you run the resulting application you’ll get:
<code> Library initialized: Now, you can use classes and functions declared here. Hello! object(C)(2) {
["array"] => array
{
[0] => integer(1)
[1] => integer(2)
[2] => integer(3)
}
["data"] => array
{
['a'] => integer(1)
['b'] => integer(2)
}
} <code>