Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    922
    Thanks
    302
    Thanked 3 Times in 3 Posts

    Question Number of objects created?

    Hi

    I was wondering if there is anyway in php to know how many objects of a class has been created?


    Thanks



    Code:
    class myclass {
    
    function __construct(){
    
    }
    
    
    function myfunc(){
    
    
    }
    
    
    
    }
    
    $obj = new myclass();

    Thanks

  • #2
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,863
    Thanks
    160
    Thanked 2,224 Times in 2,211 Posts
    You'd need to have a static member variable and increment the value from the constructor.
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

  • #3
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    922
    Thanks
    302
    Thanked 3 Times in 3 Posts
    An example would be appreciated

  • #4
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,389
    Thanks
    13
    Thanked 353 Times in 349 Posts
    PHP Code:
    class MyClass
    {
        static private 
    $selfCount 0;

        public function 
    __construct()
        {
            
    self::$selfCount++;
        }

    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #5
    Regular Coder
    Join Date
    Mar 2006
    Posts
    238
    Thanks
    3
    Thanked 37 Times in 37 Posts
    Also you would need to decrement the counter in the class destructor if you need to know how many instances of the object exists currently:
    PHP Code:
    <?php
    class myclass 
    {
     public static 
    $counter=0;
     
     public function 
    __construct()
     {
      ++
    self::$counter;
     }

     public function 
    __destruct()
     {
      --
    self::$counter;
     } 
    }

    $o1 = new myclass();
    $o2 = new myclass();
    echo 
    myclass::$counter '<br />'// outputs 2
    unset($o1);
    echo 
    myclass::$counter '<br />'// outputs 1
    ?>
    Though if you only need to know how many objects have been created no matter if they still exist or not, then decrementing should not be done of course ...

  • #6
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    This is an interesting request. There are still some question to be asked.

    Example 1:
    PHP Code:
    // Unique variable names
    // This would be 2 counted instances
    $user1 = new User;
    $user2 = new User
    Example 2:
    PHP Code:
    // Same variable names
    // Would this be 2 counted instances, or 1?
    $user = new User;
    $user = new User
    Here is an alternative solution that will count variables using the instanceof comparator. This is based upon Example 2 above returning a count of 1.

    A few gotchas:
    - It avoids array keys named GLOBALS, to avoid infinite recursion on the base scope of $GLOBALS or get_defined_vars(). This is where previous suggestions using static properties would be handier. So you'd want to avoid assigning something like $_SESSION['GLOBALS'] = new ClassName; ... which is unlikely, but entirely possible.
    - It only checks current variable values, and not the number of called constructors.
    - It will not record classes called statically (ie: User::emailExists()) unless the static method returns a class instance.

    A couple non-gotchas:
    - Classes do not require modifications to the constructor or destructor to increment/decrement counts.
    - Classes do not require a constructor or destructor.

    It also relies on scope definition.
    PHP Code:
    function count_instances$class_name, Array $scope = array() )
    {

        
    // Initiate our count
        
    $count 0;

        
    // If $class is an instance, grab the class name
        
    if ( is_object$class_name ) )
        {
            
    $class_name get_class$class_name );
        }

        
    // Iterate the current scope
        
    foreach ( $scope as $key => $value )
        {

            switch ( 
    TRUE )
            {
                
    // Avoid infinite recursion
                
    case ( 'GLOBALS' == $key ):
                    break;
                
    // Recurse into sub-arrays
                
    case is_array$value ):
                    
    $count += count_instances$class_name$value );
                    break;
                
    // Count instances
                
    case ( $value instanceof $class_name ):
                    
    $count++;
                    break;
            }

        }

        return 
    $count;


    Example 1:
    PHP Code:
    class User {};

    $user1 = new User;
    $user2 = new User;

    echo 
    count_instances'User'$GLOBALS ); // 2

    // 'User' can also be any instance of the class
    echo count_instances( new User$GLOBALS ); // 2
    echo count_instances$user1$GLOBALS ); // 2

    // $GLOBALS could also be get_defined_vars()... we just need a scope is all
    echo count_instances( new Userget_defined_vars() ); // 2 
    Example 2:
    PHP Code:
    class User {};

    $user = new User;
    $user = new User;

    echo 
    count_instances'User'$GLOBALS ); // 1 
    Example 3:
    PHP Code:
    class User {};
    class 
    Whatever {};

    $user = new User;
    $user = new Whatever;

    echo 
    count_instances'User'$GLOBALS ); // 0 
    Example 4:
    PHP Code:
    class User {};
    class 
    Whatever extends User {};

    $user = new User;
    $user = new Whatever;

    echo 
    count_instances'User'$GLOBALS ); // 1 
    Example 5:
    PHP Code:
    session_start();

    class 
    User {};

    $user1 = new User;
    $user2 = new User;

    $_SESSION['user'] = new User;
    $_POST['user'] = new User;

    echo 
    count_instances'User'$GLOBALS ); // 4 
    Example 6, using $_SESSION as the scope:
    PHP Code:
    session_start();

    class 
    User {};

    $user1 = new User;
    $user2 = new User;

    $_SESSION['user'] = new User;
    $_POST['user'] = new User;

    echo 
    count_instances'User'$_SESSION ); // 1 
    Last edited by kbluhm; 02-20-2010 at 05:18 PM.

  • #7
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,389
    Thanks
    13
    Thanked 353 Times in 349 Posts
    Quote Originally Posted by kbluhm View Post
    Example 2:
    PHP Code:
    // Same variable names
    // Would this be 2 counted instances, or 1?
    $user = new User;
    $user = new User
    obviously 2 (w/o destructor), since the constructor was executed twice. if you use the destructor decrementing, then 1.
    Last edited by Dormilich; 02-20-2010 at 05:02 PM.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #8
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Quote Originally Posted by Dormilich View Post
    obviously 2 (w/o destructor), since the constructor was executed twice. if you use the destructor decrementing, then 1.
    That question was obviously directed at the OP's ultimate desired functionality. What you're referencing is other suggestions.
    Last edited by kbluhm; 02-20-2010 at 05:24 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •