PHP - Create new class instance inside another class

  • benwade9721
  • Novice
  • Novice
  • User avatar
  • Joined: Jan 20, 2009
  • Posts: 17
  • Status: Offline

Post August 2nd, 2009, 7:31 am

Hi guys,

I was wondering if it is okay to create a new class instance inside the __construct of another class???
I tried looking it up via the almight oracle google and can't find much on it...

Code: [ Select ]
<?
class Class_One {
   
    var $name;
   
    function __construct($my_string) {
        $this->name = $my_string;
        echo 'Hello ' . $this->name;
    }
   
    function function_one() {
        echo 'Hello World';
    }
 
}
 
class Class_Two {
 
    function __construct() {
        $new_class_instance = new Class_One('Joan');
    }
}
?>
  1. <?
  2. class Class_One {
  3.    
  4.     var $name;
  5.    
  6.     function __construct($my_string) {
  7.         $this->name = $my_string;
  8.         echo 'Hello ' . $this->name;
  9.     }
  10.    
  11.     function function_one() {
  12.         echo 'Hello World';
  13.     }
  14.  
  15. }
  16.  
  17. class Class_Two {
  18.  
  19.     function __construct() {
  20.         $new_class_instance = new Class_One('Joan');
  21.     }
  22. }
  23. ?>


I am not sure how to then call the function_one() method from Class_One???

Does anyone have any resources/ideas on this???
I amn't sure if it's even ok to do this with PHP Classes.

Thanks

Ben Image
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post August 2nd, 2009, 7:31 am

  • UPSGuy
  • Lurker ಠ_ಠ
  • Web Master
  • User avatar
  • Joined: Jul 25, 2005
  • Posts: 2735
  • Loc: Nashville, TN
  • Status: Offline

Post August 2nd, 2009, 9:09 am

You're calling function_one from class_two's constructor - is that what you're inquiring about? If so, then I don't see any reason why it wouldn't be allowed. Will it run as intended?
I'd love to change the world, but they won't give me the source code.
  • benwade9721
  • Novice
  • Novice
  • User avatar
  • Joined: Jan 20, 2009
  • Posts: 17
  • Status: Offline

Post August 2nd, 2009, 11:33 am

Hi UPSGuy,

I can call using:

$my_class_two = new Class_Two;
$my_class_two->new_class_instance->function_one();


Is there any way that I can call function_one() using:

$my_class_two->function_one();

instead of

$my_class_two->new_class_instance->function_one();

???

Thanks,
Ben
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3229
  • Loc: South Africa
  • Status: Offline

Post August 5th, 2009, 10:39 am

No you can't do that unless you declare a method/function called function_one in Class_Two.
Watch me grow
  • Bogey
  • Bogey
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 8211
  • Loc: USA
  • Status: Offline

Post August 5th, 2009, 8:18 pm

You can do that
Code: [ Select ]
<?php
class one
{
    function two()
    {
        return 'Blue dog!';
    }
}

class three extends one
{
    function __construct()
    {

    }
}

$class = new three();

$class->two();
?>
  1. <?php
  2. class one
  3. {
  4.     function two()
  5.     {
  6.         return 'Blue dog!';
  7.     }
  8. }
  9. class three extends one
  10. {
  11.     function __construct()
  12.     {
  13.     }
  14. }
  15. $class = new three();
  16. $class->two();
  17. ?>

It's either implements or extends...
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3229
  • Loc: South Africa
  • Status: Offline

Post August 6th, 2009, 1:34 am

Yes you can extend the class but that is not the context of the initial illustration :)
Watch me grow
  • Bogey
  • Bogey
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 8211
  • Loc: USA
  • Status: Offline

Post August 6th, 2009, 2:56 pm

Rabid Dog wrote:
Yes you can extend the class but that is not the context of the initial illustration :)

I was under the impression the user wanted to use one function from another function without having to call two objects... this allows you to do $this->function_that_is_insdide_another_class()
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Joined: Sep 22, 2003
  • Posts: 6128
  • Loc: Seattle, WA
  • Status: Offline

Post August 6th, 2009, 3:48 pm

Yes Bogey but there's a very big difference between wrapping and extending another class.
The Beer Monocle. Classy.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3229
  • Loc: South Africa
  • Status: Offline

Post August 7th, 2009, 7:42 am

I cannot really see the purpose of wrapping the function to be honest. If class X facilitates your request then why have class Y facilitate that request as well?

The only time I can really see a use for this is when you have class X with defined function and class Y that has to make use of that function. That or you want to box a type.

Code: [ Select ]
 
public class ClassOne{
  public void SayHello(String name){
    Console.WriteLine(this.GetHello(name));
  }
 
  public String GetHello(String name){
    return String.Format("Hello: {0}",name);
  }
}
 
public class ClassTwo{
  private ClassOne _classOne = new ClassOne();
  public void SayHelloAndGreeting(String name, String greeting){
    Console.WriteLine(GetHelloAndGreeting(name, greeting));
  }
 
  public String GetHelloAndGreeting(String name, String greeting){
   return String.Format("{0} - {1}", _classOne.GetHello(name), greeting);
  }
  public ClassOne ClassOneInstance{get{return _classOne;}}
}
 
//Usage
public static void Main(String[] args){
  ClassTwo classTwo = new ClassTwo();
  classTwo.SayHelloAndGreeting("Jimmini Cricket", "Just greeting you");
  classTwo.ClassOneInstance.SayHello("Jimmini Cricket");
}
 
  1.  
  2. public class ClassOne{
  3.   public void SayHello(String name){
  4.     Console.WriteLine(this.GetHello(name));
  5.   }
  6.  
  7.   public String GetHello(String name){
  8.     return String.Format("Hello: {0}",name);
  9.   }
  10. }
  11.  
  12. public class ClassTwo{
  13.   private ClassOne _classOne = new ClassOne();
  14.   public void SayHelloAndGreeting(String name, String greeting){
  15.     Console.WriteLine(GetHelloAndGreeting(name, greeting));
  16.   }
  17.  
  18.   public String GetHelloAndGreeting(String name, String greeting){
  19.    return String.Format("{0} - {1}", _classOne.GetHello(name), greeting);
  20.   }
  21.   public ClassOne ClassOneInstance{get{return _classOne;}}
  22. }
  23.  
  24. //Usage
  25. public static void Main(String[] args){
  26.   ClassTwo classTwo = new ClassTwo();
  27.   classTwo.SayHelloAndGreeting("Jimmini Cricket", "Just greeting you");
  28.   classTwo.ClassOneInstance.SayHello("Jimmini Cricket");
  29. }
  30.  


Ok I know you probably would have extended the one class to include the multiple greetings but it is the simplest way I could think of to illustrate what I am saying.

P.S. this is why I love interfaces :) Rigid definitions :)
Watch me grow
  • IcyDragoon
  • Student
  • Student
  • No Avatar
  • Joined: Mar 12, 2008
  • Posts: 65
  • Status: Offline

Post August 21st, 2009, 1:10 am

Okay, all you guys fails to answer the question...

Its pretty simple actually.

All you need to do to call a function in a class is to use the scope resolution "::" (double colon).

Code: [ Select ]
<?php
class Class_One {
   
    var $name;
   
    function __construct($my_string) {
        $this->name = $my_string;
        echo 'Hello ' . $this->name;
    }
   
    function function_one() {
        echo 'Hello World';
    }
 
}
 
class Class_Two {
 
    function __construct() {
        //$new_class_instance = new Class_One('Joan');
        Class_One::function_one();
    }
   
    function haha() {
        Class_One::function_one();
    }
}
$Test = new Class_Two(); //in constructor
$Test->haha(); // in method, you can name it function_one if you want
Class_One::function_one(); //this works also =)
?>
  1. <?php
  2. class Class_One {
  3.    
  4.     var $name;
  5.    
  6.     function __construct($my_string) {
  7.         $this->name = $my_string;
  8.         echo 'Hello ' . $this->name;
  9.     }
  10.    
  11.     function function_one() {
  12.         echo 'Hello World';
  13.     }
  14.  
  15. }
  16.  
  17. class Class_Two {
  18.  
  19.     function __construct() {
  20.         //$new_class_instance = new Class_One('Joan');
  21.         Class_One::function_one();
  22.     }
  23.    
  24.     function haha() {
  25.         Class_One::function_one();
  26.     }
  27. }
  28. $Test = new Class_Two(); //in constructor
  29. $Test->haha(); // in method, you can name it function_one if you want
  30. Class_One::function_one(); //this works also =)
  31. ?>
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3229
  • Loc: South Africa
  • Status: Offline

Post August 21st, 2009, 2:26 am

Yes it is possible but it is just plan nasty. That is what we were trying to point out. Kinda like if someone asks you how to blow their head off, pretty simple to do but you don't want to encourage it.
Watch me grow
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13455
  • Loc: Florida
  • Status: Offline

Post August 21st, 2009, 3:38 am

I wasn't going to get involved in this subject, but it seems that call_user_func_array has become un-depreciated and can't resist an opportunity to use it. :)

Code: [ Select ]
<?php
 
/*
    Utility class #1
*/
class hammer
{
    public function bang(){
        echo 'Bang! ';
        return;
    }
    public function pry(){
        echo 'Pry! ';
        return;
    }
}
 
/*
    Utility class #2
*/
class screwdriver
{
    public function loosen(){
        echo 'Loosen! ';
        return;
    }
    public function tighten(){
        echo 'Tighten! ';
        return;
    }
}
 
/*
    Implementer of utility classes
*/
class handyman
{
    /*
        A place to keep our utilities
    */
    public $toolbelt = array();
 
    public function __construct($tools = array())
    {
        foreach($tools as $tool)
        {
            /*
                http://www.php.net/get_class
                Make sure we only have one of any given tool, does not _have_ to be this way
            */
            $this->toolbelt[get_class($tool)] = $tool;
        }
        return $this;
    }
 
    /*
        http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
    */
    public function __call($method_name, $args)
    {
        foreach($this->toolbelt as $tool)
        {
            /*
                http://www.php.net/is_callable
                See if the utility object has a callable method matching the one asked for
            */
            if(is_callable(array($tool, $method_name)))
            {
                /*
                    http://www.php.net/call_user_func_array
                    Forward the method call to the utility object along with the arguments
                */
                return call_user_func_array(array($tool, $method_name), $args);
            }
        }
        /*
            http://www.php.net/trigger_error
        */
        trigger_error("Do not have a tool that can $method_name!", E_USER_ERROR);
    }
}
 
$me = new handyman(array(new hammer(), new screwdriver()));
 
$me->bang();
$me->pry();
$me->tighten();
$me->loosen();
$me->gitrdone();
 
?>
  1. <?php
  2.  
  3. /*
  4.     Utility class #1
  5. */
  6. class hammer
  7. {
  8.     public function bang(){
  9.         echo 'Bang! ';
  10.         return;
  11.     }
  12.     public function pry(){
  13.         echo 'Pry! ';
  14.         return;
  15.     }
  16. }
  17.  
  18. /*
  19.     Utility class #2
  20. */
  21. class screwdriver
  22. {
  23.     public function loosen(){
  24.         echo 'Loosen! ';
  25.         return;
  26.     }
  27.     public function tighten(){
  28.         echo 'Tighten! ';
  29.         return;
  30.     }
  31. }
  32.  
  33. /*
  34.     Implementer of utility classes
  35. */
  36. class handyman
  37. {
  38.     /*
  39.         A place to keep our utilities
  40.     */
  41.     public $toolbelt = array();
  42.  
  43.     public function __construct($tools = array())
  44.     {
  45.         foreach($tools as $tool)
  46.         {
  47.             /*
  48.                 http://www.php.net/get_class
  49.                 Make sure we only have one of any given tool, does not _have_ to be this way
  50.             */
  51.             $this->toolbelt[get_class($tool)] = $tool;
  52.         }
  53.         return $this;
  54.     }
  55.  
  56.     /*
  57.         http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
  58.     */
  59.     public function __call($method_name, $args)
  60.     {
  61.         foreach($this->toolbelt as $tool)
  62.         {
  63.             /*
  64.                 http://www.php.net/is_callable
  65.                 See if the utility object has a callable method matching the one asked for
  66.             */
  67.             if(is_callable(array($tool, $method_name)))
  68.             {
  69.                 /*
  70.                     http://www.php.net/call_user_func_array
  71.                     Forward the method call to the utility object along with the arguments
  72.                 */
  73.                 return call_user_func_array(array($tool, $method_name), $args);
  74.             }
  75.         }
  76.         /*
  77.             http://www.php.net/trigger_error
  78.         */
  79.         trigger_error("Do not have a tool that can $method_name!", E_USER_ERROR);
  80.     }
  81. }
  82.  
  83. $me = new handyman(array(new hammer(), new screwdriver()));
  84.  
  85. $me->bang();
  86. $me->pry();
  87. $me->tighten();
  88. $me->loosen();
  89. $me->gitrdone();
  90.  
  91. ?>


Code: [ Select ]
joebert@home:~/Desktop$ php -f _.php
Bang! Pry! Tighten! Loosen!
Fatal error: Do not have a tool that can gitrdone! in /_.php on line 79
  1. joebert@home:~/Desktop$ php -f _.php
  2. Bang! Pry! Tighten! Loosen!
  3. Fatal error: Do not have a tool that can gitrdone! in /_.php on line 79
Strong with this one, the sudo is.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3229
  • Loc: South Africa
  • Status: Offline

Post August 21st, 2009, 4:19 am

OUCH! Where is my 9mm, can anyone show me how to put a hole in my head because after reading that I am sure I have internal bleeding!
Watch me grow
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13455
  • Loc: Florida
  • Status: Offline

Post August 21st, 2009, 4:38 am

I wonder what the performance hit of using __call is, for starters.
Strong with this one, the sudo is.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3229
  • Loc: South Africa
  • Status: Offline

Post August 21st, 2009, 4:52 am

Probably the same as any reflection, because that is effectively what it is doing
Watch me grow
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post August 21st, 2009, 4:52 am

Post Information

  • Total Posts in this topic: 16 posts
  • Users browsing this forum: No registered users and 228 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.