ok, so if we were talking Java, perhaps you are looking for
information that allows you to build 'accessor' and 'mutator' methods?
If so, then your example should work (syntax aside). Here's another
'test' example that I just whipped up and tested that shows you can
use any method name you wish.

As I said previously, accessor/mutator methods are exactly what I am looking for. I do like the idea of having a public 'interface' (for the lack of a better word) to a private property. I don't particularly care for using just the __set() and __get() methods because they are too arbitrary. If I needed to do any specific checking or formatting for a property, either in defining or returning the value, I'd have to have a big giant switch() statement. So here is a roundabout solution that I got the idea/code for while researching this issue:

class MyClass {

 private $_bob;

 // Private so all property access is done through the
 // __set() and __get() methods
 private function setBob( $bob ) {
   $this->_bob = $bob;

 }
 private function getBob() {
   return $this->_bob;

 }

 function __get( $var ) {
   $methodName = 'get' . $var;
   if( method_exists( $this, $methodName )) {
     return call_user_func( array( $this, $methodName ));

   } else {
     throw new Exception( 'Method [' . $methodName . '] does not exist' );

   }
//    echo "In __get( $var )\n";
 }

 function __set( $key, $var ) {
   $methodName = 'set' . $key;
   if( method_exists( $this, $methodName )) {
     call_user_func( array( $this, $methodName ), $var );

   } else {
     throw new Exception( 'Method [' . $methodName . '] does not exist' );

   }
//    echo "In __set( $key, $var )\n";
 }

 function __call( $method, $args ) {
// echo 'Calling [' . $method . '] with args: [' . print_r( $args, TRUE ) . ']';

 }
}

try {
 $myClass = new MyClass();
 $myClass->Bob = 'JoeBobBriggs' ;
 echo '$myClass: <pre>' . print_r( $myClass, TRUE ) . '</pre>';
 echo $myClass->Bob . '';

} catch( Exception $e ) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";

}

Now I can do whatever checking I need to do in the setBob() method and any formatting in the getBob() method.

The above is not my original idea and I wish I could remember the name of the person to thank for pointing me in this direction. :|

thnx,
Chris
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to