DiigIT | IT Community
No Profile Image
Welcome Guest
New User? Register | Login

Instantiating objects in php

By: Sunil | 22 Sep 2008 2:18 pm

Hi everyone. I'm a .Net developer and brand new to php. I've read
through most of the php manual and in doing so realized there are a lot
of similarities between c# and php. Anyway I have a specific question
about my subject. I ran across an issue while trying to instantiate an
object in a class. This is what I did.

<?php

include 'StringBuilder. php';

class ThisClass($someVar)
{
private $sb = new StringBuilder( );

public function SomeFunction( )
{
$sb.append(' Text');
$sb.append(' Text');
echo $sb->toString( );
}
}

?>

}

I had to fix this by placing the object instantiation within a function
like so:

<?php

include 'StringBuilder. php';

class ThisClass($someVar)
{
private $sb;

public function SomeFunction( )
{
$sb = new StringBuilder( );

$sb.append(' Text');
$sb.append(' Text');
echo $sb->toString( );
}
}

?>

}

I suppose the best way to handle this is to instantiate the object in
the constructor but I was wondering if anyone had any idea why this is
necessary in the first place?

Comments

Hey dude

you can not pass parameters to class as you have done like
class ThisClass($someVar)

insted you can create a constructor and then pass while you create the
object of the class as given below
============ =====
this_class.php

class ThisClass()
{

public function __construct( $comeVar) {
private $sb = new StringBuilder( );
}

public function SomeFunction( )
{
$sb.append(' Text');
$sb.append(' Text');
return $sb->toString( );
}
}
------------ --------- ----
this_class_caller. php
//initiate teh class object of the TestClass

$_this_cladd = new ThisClass($someVar) ;
print ($_this_cladd- >SomeFunction) ;

============ ======

Let em know if u need anything else
Regards
By: Manoj | 22 Sep 2008

Leave a comment

Enter the text in the image
img
Can't read?
Type the characters you see in the picture below.


Close Move