Reputation: 28434
I read several questions and answers for other languages, but did not see any specifically for PHP.
Would the following be valid in PHP?
class foo
{
// constructor, etc..
public function bar()
{
$newFoo = new foo();
// do something
}
}
Upvotes: 1
Views: 313
Reputation: 9754
best way to know if something is valid in PHP is to use this function in your header file:
<?php
error_reporting(E_ALL|E_NOTICE);
?>
Even PHP will report failures, such as not using "isset ()".
Other practices:
Always use $_GET
, $_POST
instead of global
Do not use this: $_GET["test"]
this is the best $_GET['test']
Always read the PHP documentation to see if the function is deprecated (doc: http://www.php.net/manual)
Note:
your "constructor" is "valid".
Upvotes: 0
Reputation: 175038
Yes, it would be valid. You can create nested sets of objects. (Though doing it in the constructor would cause an infinite recursion!)
Extra! You can even link an object to itself!
$this->myself = $this;
And it would link to the same object.
Upvotes: 1
Reputation: 3904
Short answer: Yes it works!
You can instantiate your Objects in almost any place of your php code. Inside a class method is not different, but you must make sure to include your class file first if it's a different class, something like
<?php
require_once './foo.class.php';
class bar{
//class stuff
public doThingsWithFoo(){
$foo = new foo();
}
}
?>
In your particular case you seems to be searching for the $this keyword. From the manual:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
In your example then:
class foo
{
// constructor, etc..
public function bar()
{
$this->useAMethodFromThisClass();
// do something
}
}
But there's nothing (except maybe common sense) in using another instance of the same object in a method of the same class, much like you are doing:
class foo
{
// constructor, etc..
public function bar()
{
$newFoo = new foo();
// do something with this instance of foo that you cannot do using $this
}
}
I hope it helped. Cheers
Upvotes: 1
Reputation: 4637
Yes, that's valid, as long as you don't create an object of the same type in the constructor.
Upvotes: 1