Instantiating a Scalar Variable?

The book I am reading has the following code…


  $className = str_replace(' ', '',
                           ucfirst(str_replace('_', ' ',
                                               $params['filename'])));

  // Create presentation object
  $obj = new $className();

As far as I know, $className is a scalar (i.e. string) variable?!

So how can you instantiate it and assign it to $obj?

TomTees

These are equivalent:


$obj = new SomeGreatClass();

$className = 'SomeGreatClass';
$obj = new $className();


Just a way to dynamically specify a class.

That will work as long as the value in $className matches an existing class.

See Example 3 in the documentation for a new class

That link doesn’t work.

Okay, but backing up, you guys aren’t answering my question…

Classes are supposed to be complex data structures with data and methods.

In the code I posted, $className is just a String.

So how can you treat it as a class and instantiate it?

TomTees

You can not. It is only when the class already exists that you can use a variable string that matches the already-existing class, to instantiate that class.

What is the book you’re reading, and at which page does that info occur?

This may make the concept a little more evident:


class Foo {
	private $_name = 'A Foo';
}

class Bar {
	private $_name = 'A Bar';
}

$obj = array('Foo','Bar');
$objects = array();
foreach($obj as $className) {
	$objects[] = new $className();
}

echo '<pre>',print_r($objects),'</pre>';

Okay, but if you did that, how would the class be made to equal a string?! (Not sure if that is the best way to say it!)

What is the book you’re reading, and at which page does that info occur?

“Beginning PHP and MySQL E-commerce” but I doubt you’d have that book.

Here is a larger block of code…


<?php
// Plug-in functions inside plug-in files must be named: smarty_type_name
function smarty_function_load_presentation_object($params, $smarty)
{
  require_once PRESENTATION_DIR . $params['filename'] . '.php';

[b][COLOR="Blue"]  $className = str_replace(' ', '',
                           ucfirst(str_replace('_', ' ',
                                               $params['filename'])));
[/COLOR][/b]
  // Create presentation object
[COLOR="Red"][B]  $obj = new $className();
[/B][/COLOR]
  if (method_exists($obj, 'init'))
  {
    $obj->init();
  }

  // Assign template variable
  $smarty->assign($params['assign'], $obj);
}
?>

As I see it, the blue first occurrence, $className is primitive string type.

In the red second occurrence, $className is some predefined class (i.e. has properties and methods) that is being assigned to $obj.

Therefore, I do not see how you can instantiate a variable that was earlier defined as a primitive string data-type.

TomTees

The string name in $className is the name of a class that is in the file called
PRESENTATION_DIR . $params[‘filename’] . ‘.php’

This is essentially the same as variable variables. Instead of the name of the variable or class being hard coded into the PHP it is the value of another variable.


$my_variable = 'STRING VALUE';
$var_to_use = 'my_variable';

echo $$var_to_use; //outputs STRING VALUE

or using object members


class Foo
{
   protected $bar = 'Hello World';

   public function get() {
     $member = 'bar';
     return $this->$member; //accesses $this->bar
   }
}

Oh ye of little faith.

The code you’re having trouble understanding is on page 103. Earlier on page 100 is a partial explanation

Smarty plug-in function: The Smarty plug-in function is referenced from the Smarty design template, and its role is to supply the template with data it needs to display. In our project, the same Smarty plug-in function (function.load_presentation_object.php) will be loaded by all Smarty design templates. However, the Smarty plug-in function will return different results depending on the parameters it is invoked with.

Later on, at page 105 there is also a “How it works” section that you should read through too.

You may find the book’s errata to be of some good use, as well as the [url=“http://www.smarty.net/forums/index.php”]Smarty Forums.

How did you come to that conclusion?

TomTees

I came to that conclusion due to $params[‘filename’] being used to do two things. Those two things were:

[list][]to load a file
[
]and to instantiate a class based on the filename[/list]

Wow! We have a librarian here!

I saw this post after I made my last post. After re-reading the code for the 20th time, I finally see how it works?! (:

Some follow-up questions…

1.) I don’t understand this bolded code…

<?php
// Plug-in functions inside plug-in files must be named: smarty_type_name
function smarty_function_load_presentation_object($params, $smarty)
{
  require_once PRESENTATION_DIR . $params['filename'] . '.php';

  $className = str_replace(' ', '',
                           ucfirst(str_replace('_', ' ',
                                               $params['filename'])));

  // Create presentation object
  $obj = new $className();

[B][COLOR="Blue"]  if (method_exists($obj, 'init'))
  {
    $obj->init();
  }
[/COLOR][/B]
  // Assign template variable
  $smarty->assign($params['assign'], $obj);
}
?>


When would ‘init’ NOT exist??

2.) I don’t understand this bolded code…

<?php
// Plug-in functions inside plug-in files must be named: smarty_type_name
function smarty_function_load_presentation_object($params, $smarty)
{
  require_once PRESENTATION_DIR . $params['filename'] . '.php';

  $className = str_replace(' ', '',
                           ucfirst(str_replace('_', ' ',
                                               $params['filename'])));

  // Create presentation object
  $obj = new $className();

  if (method_exists($obj, 'init'))
  {
    $obj->init();
  }

  // Assign template variable
[B][COLOR="Blue"]  $smarty->assign($params['assign'], $obj);[/COLOR][/B]
}
?>

What are we assigning? To where? And why?

3.) Since you obviously know Smarty, and since you have the same book, what is your advice to me as far as using Smarty and the author’s code to build my first e-commerce site?

I have been speaking to a few people who seem to think that Smarty and this author’s code are making things more difficult than need be.

My goal is to learn how to code this myself, versus “configuring” something like Magento.

I am open to a new approach, as long as it is a complete solution and not just bits and pieces.

TomTees

yup and i am one of them…:smiley:
i dont quite agree with that framework.
I read that book 1.5 years ago i guess

Problems
It used too personal style…you wont see that style in any where other than that book :smiley:
It has strange way of loading view and writing models…
It introduces too many functions every now and then…
It even complicates MVC …it says 3 tier but infact it has 4 tier app development…
he divides Model into 4 parts itself introducing stored procedures in mysql…

and some others as well…
but i gave up that book so dont remember all…

Talking about the framework,see this from that framework
{load_presentation_object filename=“departments_list” assign=“obj”}
{* Start departments list *}

what is does loads a file name called departments_list and assign it to obj…
Convention used their is quite strict and quite personal…
and much easier in cakephp and zend …lol

well init() here is like contructor function which automatically does something…
(i have seen it in dotnet actually)

see these line in the book
The init() method in DepartmentsList populates a public member of the class ($mDepartments) with an
array containing the list of departments and another public member containing the index of the currently selected
department ($mSelectedDepartment).

Those values are being passed to view of that page…so that it can be processed or echoed…

My suggestion:If you really feel and want to get started in ecommerce and feel you can really do it…
go with magenta…customize it…

Having said that ,nothing against book or great authors…i know they are pros…but just may be i feel book could have been better …and i think it was published before the other framework boomed…

That would occur when the class doesn’t exist, which is most likely caused by being provided with a bad filename.

Smarty is being told that the $obj is the object that is currently assigned. A reference to $obj is being passed to Smarty, so that Smarty knows what to call.

I’d say that Frank has answered this one quite well.