Jump to content

Recommended Posts

Hi,

 

is it possible to create an object inside a class?...

 

say i have 2 class...

 

class a {

  var $val;

   some code

}

 

class b {

$myobject = new a;

$myobject->val=1;

...............

}

 

will the above work ??... first of all .. is it possible to do like above ?....

 

Please advice..... in my code i used something like this but its not working..

 

 

Jaikar

 

Link to comment
https://forums.phpfreaks.com/topic/43142-creating-an-object-inside-a-class/
Share on other sites

Yeah what you have done should definitely work.

 

If it's not working, post some code and maybe we can suggest what may be going wrong.  Also, make sure you PHP version is not something that isn't too old.  I wouldn't necessarily recommend using anything object oriented in PHP 3 or earlier.

it should work fine.  this code outputs "WOOT":

<?php

$test = new bar("WOOT");

class foo
{
var $test;

function foo($test){
	$this->test = $test;
}

function print_object(){
	echo $this->test;
}
}

class bar
{
var $object;

function bar($test){
	$this->object = new foo($test);

	$this->object->print_object();
}
}

?>

post your code so we can give you some guidance.

Thanks najibk , idevlabsdotcom ....

 

my code was similar to what idevlabsdotcom gave... now i can say i made a mistake....

 

but why $this->test = $test is inside a function ?... why not set outside the function.. what is where i got the error....

 

i set the value outside the function.. like

 

class foo

{

var $test;

 

            $this->test = $test;  ???????????????//

 

function print_object(){

echo $this->test;

}

}

 

why i am getting the error if i do thin.....  ???

well actually that is a very good question xD, it probably has something to do with those 0's and 1's called bits xD, and ofcourse the class scope which only allows to declare properties (which represent your variables) or methods (which represent functions)

 

for more information on programming in OOP:

http://www.phpfreaks.com/tutorials/150/0.php

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.