tags:

views:

59

answers:

3

Sometimes it's difficult to explain in human language what you want to do in programming, but I will try...

Please explain to me, how can I implement the following logic. Suppose we have a template class:

$obj1=new Tmpl($somevar1, $somevar2, ...);
//we then add a new file to template
//as we don't have any files yet, new object won't created
$obj1->AddTmpl('file1.tmpl');
//we add a second file to template,
//it will be independent template
//but all properties from $obj1 must be available
$obj2=$obj1->AddTmpl('file2.tmpl');

$obj1->printTmplFile(); //should output file1.tmpl
$obj2->printTmplFile(); //should output file2.tmpl

$obj2->printInitialVars(); 
//will print $somevar1, $somevar2 constructed for $obj1;
//$obj1 of course must have these variables available also

So, the purpose of it is in creating new object for each new file of a template. Each new object should have all set of properties which have been established for old object. So, in this case, for example, we will not call a constructor each time with the same arguments. Also only $obj1 can create a copy of itself. And if it is first call to method AddTmpl, then we don't create new copy.

It is possible to do?

A: 

I'm not sure if it's what you're trying to do, but have a look at php's object cloning.

cypher
+2  A: 

(Here I assume that the AddTmpl function does not return a copy of the object itself.)

The following line is wrong. You are saving the result of the AddTmpl function into $obj2, this does not return a copy of $obj1.

$obj2=$obj1->AddTmpl('file2.tmpl');

You have to use cloning like this:

$obj2 = clone $obj1;
$obj2->AddTmpl('file2.tmpl');

Note that after the cloning, $obj2 and $obj1 are totally independant and any changes made to one will not be reflected to the other. This is the intended purpose!

More information about cloning: http://php.net/manual/en/language.oop5.cloning.php

Edit: fixed typo in code

Weboide
Thanks, but I found it's more pretty to put cloning inside a class, like return(clone $this); and then I have also magic __clone() method to unset some unnecessary properties for a new clone.
Starmaster
Indeed, it is nice to have a copy() method.
Weboide
A: 

Possible yes, (with clone in the addTmpl() function)

But thats not adviseable, the API you're showing in the question not directly understandable / selfexplanatory.

Other solutions are:

$tpl = new Tmpl();
$tpl->render('template1.tmpl'); 
$tpl->render('template2.tmpl'); 

Or

$tpl = new Tmpl();
$tpl->setTmpl('template1.tmpl');

$tpl2 = clone $tpl;
$tpl2->setTmpl('template2.tmpl');

$tpl1->render();
$tpl2->render();
Bob Fanger