PHP Classes
elePHPant
Icontem

File: testdynclass.php

Recommend this page to a friend!
  Classes of Chris Jeffries  >  dynClass  >  testdynclass.php  >  Download  
File: testdynclass.php
Role: Example script
Content type: text/plain
Description: Test program for dynClass
Class: dynClass
Extends stdClass to have callable functions
Author: By
Last change: Tests and illustrates the use of dynClass including use of '$this'
Date: 2 years ago
Size: 2,322 bytes
 

Contents

Class file image Download
<?php
//test of dynclass vs stdClass
include "dynClass.class.php";
echo
'<h1>Initialising classes</h1>';
$dyn = new dynClass(array("z"=>"foo", "method1"=>function(){ return "Method1 called";}));
$std = new stdClass(array("z"=>"foo"));

echo
'<p>dynClass understands initialization from array</p>';
echo
"dyn ->z : " . $dyn->z;
echo
'<p>But stdClass does not</p>';
echo
"std ->z : " . $std->z;

$dyn->a = array(1,2,3,4,"ttt");
$std->a = array(1,2,3,4,"ttt");

$dyn->b = true;
$std->b = true;

$dyn->c = "string";
$std->c = "string";

$testclass = new stdClass();
$testclass->property = "test property";

$dyn->o = $testclass;
$std->o = $testclass;

$dyn->f = function($parm='no value passed') { return "lambda passed $parm"; } ;
$std->f = function($parm='no value passed') { return "lambda passed $parm"; } ;

$u = function($parm='no value passed') { return "Saved lambda returned $parm"; } ;
$dyn->u = $u;
$std->u = $u;

$t = function($parm='z') {
    return
$this->$parm;
    } ;
$dyn->t = $t;

global
$glob;
$glob = "This is a global";
$g = function () {
    global
$glob;
    return
"This is from outside: $glob";
     } ;

$dyn->g = $g;
$std->g = $g;

$dyn->i = 55;
$std->i = 55;

$dyn->e = 55E6;
$std->e = 55E6;

echo
"<h1>Var_dump of stdClass</h1><pre>";
var_dump($std);

echo
"</pre>var_dump of dynClass</h1><pre>";
var_dump($dyn);

echo
"
</pre><h1>Test lambdas added to dynClass as properties</h1><pre>
directly assigned lambda f :
{$dyn->f}
indirectly assigned lambda u :
{$dyn->u}
lambda referencing global g :
{$dyn->g}
lambda referencing \$this t :
{$dyn->t}
lambda at instantiation method1:
{$dyn->method1}
</pre>"
;

echo
"
</pre><h1>Test lambdas added to dynClass as methods</h1><pre>
directly assigned lambda f :
{$dyn->f("-value-")}
indirectly assigned lambda u :
{$dyn->u("-value-")}
lambda referencing global g :
{$dyn->g("-value-")}
lambda referencing \$this t :
{$dyn->t("z")}
</pre><h1>The remainder are going to fail</h1>"
;
try {
    echo
"</pre><h1>Test lambdas added to stdClass as properties</h1><pre>
    f :
{$std->f}
    u :
{$std->u}
    g :
{$std->g}
    </pre>"
;

    echo
"
    </pre><h1>Test lambdas added to stdClass as methods</h1><pre>
    f :
{$std->f("-value-")}
    u :
{$std->u("-value-")}
    g :
{$std->g("-value-")}
    </pre>"
;
}
catch (
Exception $e) {
    echo
"<br>As anticipated, this error occurred: $e";
}
?>