PHP - Create new class instance inside another class

  • benwade9721
  • Novice
  • Novice
  • User avatar
  • Posts: 17

Post 3+ Months Ago

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
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • UPSGuy
  • Lurker ಠ_ಠ
  • Web Master
  • User avatar
  • Posts: 2733
  • Loc: Nashville, TN

Post 3+ Months Ago

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?
  • benwade9721
  • Novice
  • Novice
  • User avatar
  • Posts: 17

Post 3+ Months Ago

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
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

No you can't do that unless you declare a method/function called function_one in Class_Two.
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

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...
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Yes you can extend the class but that is not the context of the initial illustration :)
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

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()
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

Yes Bogey but there's a very big difference between wrapping and extending another class.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

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 :)
  • IcyDragoon
  • Student
  • Student
  • IcyDragoon
  • Posts: 65

Post 3+ Months Ago

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
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

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.
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13503
  • Loc: Florida

Post 3+ Months Ago

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
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

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!
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13503
  • Loc: Florida

Post 3+ Months Ago

I wonder what the performance hit of using __call is, for starters.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Probably the same as any reflection, because that is effectively what it is doing
  • yenk
  • Born
  • Born
  • yenk
  • Posts: 1

Post 3+ Months Ago

Hi,

I Know That This Post Is Old to Think That Ive benwade9721 want to DO IS Something like:
Code: [ Select ]
<?
class Class_One {
 
  var $name;

  public static function getInst ($my_string) {
    return new Class_One ($my_string);
  }
 
  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');
    $new_class_instance = Class_one::getInst ('Joan');
    $new_class_instance->function_one ();
  }
}
?>
  1. <?
  2. class Class_One {
  3.  
  4.   var $name;
  5.   public static function getInst ($my_string) {
  6.     return new Class_One ($my_string);
  7.   }
  8.  
  9.   function __construct($my_string) {
  10.     $this->name = $my_string;
  11.     echo 'Hello ' . $this->name;
  12.   }
  13.  
  14.   function function_one() {
  15.     echo 'Hello World';
  16.   }
  17. }
  18. class Class_Two {
  19.   function __construct() {
  20.     //$new_class_instance = new Class_One('Joan');
  21.     $new_class_instance = Class_one::getInst ('Joan');
  22.     $new_class_instance->function_one ();
  23.   }
  24. }
  25. ?>

in hope itll Be Helpful

Post Information

  • Total Posts in this topic: 16 posts
  • Users browsing this forum: Liamw411 and 61 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
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.