Using PHP library from C#

Requirements: Nightly build from October 8, 2006 or later (10-08-2006 Nightly Build).

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, place the following two scripts into some directory

  include "ClassC.php";

  function f()
    echo "Hello!\n";

  echo "Library initialized: Now, you can use classes and functions declared here.\n";

class C
  public $array = array(1,2,3);
  function __construct($data)
    $this->data = $data;

and run

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():

            // 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:

To build the C# program, just run

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /reference:"ClassLibrary.dll" /reference:"C:\Program Files\Phalanger v2.0\PhpNetCore.dll" /out:ConsoleApplication.exe /target:exe Program.cs

And that's it. If you run the resulting application you get:

Library initialized: Now, you can use classes and functions declared here.
  ["array"] => array
    [0] => integer(1)
    [1] => integer(2)
    [2] => integer(3)
  ["data"] => array
    ['a'] => integer(1)
    ['b'] => integer(2)

Last edited Oct 9, 2006 at 6:11 AM by TomasMatousek, version 10


No comments yet.