Classes/Object Funzioni

Indice dei contenuti

add a note

User Contributed Notes 16 notes

up
8
gateschris at yahoo dot com
25 years ago
[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

<?php
class foo {
 function foo () { }
 function a () { }
}

class bar extends foo {
 function bar () { }
 function a () { }
}

lala = new Bar();
?>
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.
up
3
asommer*at*as-media.com
23 years ago
Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!
up
2
covertka at muohio dot edu
21 years ago
To pillepop2003 at yahoo dot de:

I have the same issue.  I have a base class that manages database tasks for a number of child classes.  One of the functions in the base class is a find() method that returns instances of the child classes.  Since find() is usually called as a static method, it needs to know the name of the child class.  As you've found, this appears to be impossible to get in an easy fashion.

The only way I've found to get the child class name is to use the debug_traceback() function.  This requires me to have a find() method in every child class, but it does work.

Here's an example:

<?php
  require_once("Application.php");

  class parentClass {
    function find() {
      $className = NULL;
      foreach (debug_backtrace() as $bt) {
        if ($bt['function'] == __FUNCTION__) {
          $className = $bt['class'];
        }
      }

      // here should be some code to find the proper id, let's assume it was id 1
      $id = 1;
      return new $className($id);
    }
  }
  
  class foo extends parentClass {
    function __construct($id) {
      $this->id = id;
    }
    
    function find() {
      return parent::find();
    }
  }
  
  class bar extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }
  
  $a = foo::find();
  printf("Type for \$a: %s<br/>\n", get_class($a));
  $b = bar::find();
  printf("Type for \$b: %s<br/>\n", get_class($b));
?>
up
2
zidsu at hotmail dot com
23 years ago
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

class Some_class {
  var $value = 3;
  function add_value ($input_param) {
    return include ("path/some_file.php");
  }
}

And your included file:

$input_param += $this->value;
return $input_param;

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully :P

Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
up
0
http://sc.tri-bit.com/ StoneCypher
21 years ago
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function.  Let's assume you're doing something like this:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {
      case 'stuff'      : return new Stuff($instancedata);
      case 'otherstuff' : return new Otherstuff($instancedata);
    }

  }

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {

      case 'stuff'      : return array('typeis'=>'stuff',      'instance'=>new Stuff($instancedata));
      case 'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

    }

  }

?>

Nice 'n simple.  It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior.  If you move to PHP5, the static keyword solves your problem cleanly.
up
0
ettinger at consultant dot com
22 years ago
Re: Looking for an uninstantiated class

# Loads data from a table into a class object
class LFPDataFactory extends LFPObject {
        var $object;
        var $class;
        var $table;
        function LFPDataFactory($args) {
                $this->unpackArgs($args); // assigns locals from $args
                if (in_array(strtolower($this->class), get_declared_classes())) {
                        $this->object = new $this->class;
                        // assemble the columns in the table...
                        // select their values and put them in our new object...
                } else { trigger_error("Class ".$this->class." not found", E_USER_ERROR); }
        }
}
$r = new LFPDataFactory("class=LFPLayout,table=layout");
$new_obj = $r->object; // this is a LFPLayout object.
print_r($new_obj);

This class looks to see if the class exists, then instantiates it -- a declared class is not the same as an instantiated class. As long as LFPLayout exists somewhere in the scripts, get_declared_classes() will find it. Remember strtolower on compare, however.

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I've left out the actual code to do the selection/insertion).
up
-1
Dennis
16 years ago
We have an array with many objects in a style like

<?php

$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel

// [ ... ]

?>

$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.

Because there is no function in php api, we made the following function.

Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.

Warning: function is very slow and should only be called if it's necessary for debugging reasons:

<?php

/**
 * returns resource- and object-ids of all objects in an array
 * 
 * @param array $array
 * @return array
 */
function getObjectInformation(Array $array)
{
    // start output-buffering
    ob_start();
    
    // create an var_dump of $array
    var_dump($array);
    
    // save the dump in var $dump
    $dump = ob_get_contents();
    
    // clean the output-buffer
    ob_end_clean();
    
    // delete white-spaces
    $dump = str_replace(' ', '', $dump);
    
    // define the regex-pattern
    // in our case, all objects look like this:
    //
    // object(ClassName)#1(1){
    // ["id":protected]=>
    // string(1)"1"
    $pattern  = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
    $pattern .= '\["id":protected\]=>\\n';
    $pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';
    
    // search for all matches
    preg_match_all($pattern, $dump, $regs);
    
    // sort all mathes by class name, object id and then resource id
    array_multisort($regs[1], SORT_ASC, SORT_STRING,
                    $regs[3], SORT_ASC, SORT_NUMERIC,
                    $regs[2], SORT_ASC, SORT_NUMERIC);
    
    // cache the last match
    $lastMatch = array();
    
    // the return value
    $return = array();
    
    // loop through the matches
    for ($i = 0; $i < sizeof($regs[0]); $i ++) {
        
        // check if the current match was not visited before
        if (