Jump to content

Identifying classes


poshpaws

Recommended Posts

After reading up on OOP in PHP5, I'm now thinking of how I can apply it to where I used to use procedural code. I understand the textbook examples (though they usually tend to be quite basic) and the idea of designing classes according to 'real world' thinking, but when I try and think how to switch my site to OOP I get a bit lost. I can't really get my head round identifying classes (where there just used to be functions) and child classes.

 

I'm looking at some PHP frameworks to try to understand this better, but can anyone suggest any other ways?

Link to comment
Share on other sites

Classes are great if you want to encrypt code or provide a layer of protection to say.

 

Let's say we have a user class, this class can house the user's password which we only want an admin/that user to see not the rest of the world. We can make this variable a protected or private variable to the class and make it so that you have to go through a function which checks that to return the variable.

 

But really it all depends on how you want to use it. For certain projects it works great, for others it's userless.

 

There are many more reasons why classes are good than what I explained, that was just one.

Link to comment
Share on other sites

:) im a noobie too in OOP approach..

correct me if im worng..From what I have read to some articles in the net and my understanding on how to apply OOP.. you must view things as an object(literally). for example:

 

object:cellphone

->properties: casing, keypad, screen, battery

->behavior: text and call

-> now the question is how are you gonna make the 'properties' in order for the object to do their what they must do(behavior)

Link to comment
Share on other sites

:) im a noobie too in OOP approach..

correct me if im worng..From what I have read to some articles in the net and my understanding on how to apply OOP.. you must view things as an object(literally). for example:

 

object:cellphone

->properties: casing, keypad, screen, battery

->behavior: text and call

-> now the question is how are you gonna make the 'properties' in order for the object to do their what they must do(behavior)

 

Yeah, that is sort of what it is about. Here is an example:

<?php
/**
* Phone
* 
* A basic phone that can dial other phones.
*/
class phone
{
/**
 * Number
 * 
 * The number of this phone
 *
 * @access private
 * @var int
 * @see phone::get_number()
 * @see phone::change_number()
 */
private $number;

/**
 * Phone constructor
 * 
 * Sets the number of the phone when a new instance of phone is created.
 *
 * @access public
 * @param int $number
 */
public function __construct($number)
{
	$this->set_number($number);
}

/**
 * Get number
 * 
 * Will get the number of the current phone
 *
 * @access public
 * @return int
 */
public function get_number()
{
	return $this->number;
}

/**
 * Set number
 *
 * @access public
 * @param int $number
 * @return bool
 */
public function set_number($number)
{
	if(!empty($number) && intval($number) != 0)
	{
		$this->number = $number;
		return true;
	}
	else {
		echo "Invalid number";
		return false;
	}
}

/**
 * Dial number
 * 
 * Dials a number to call another phone
 *
 * @access public
 * @param int $number
 * @return bool
 */
public function dial_number($number)
{
	if($number == $this->number)
	{
		echo "You cannot call yourself!";
		return false;
	}
	else {
		// stuff here
	}
}
}

/**
* Wireless phone
*
* Same as phone except that it is wireless and therefore has a battery.
*/
class wireless_phone extends phone
{
/**
 * Battery type
 * 
 * This is the type of the battery. It can be either 1, 2 or 3. Highest number is best battery.
 *
 * @access private
 * @var int
 */
private $battery_type;

/**
 * Wireless phone constructor
 *
 * @access public
 * @param int $number
 * @param int $battery_type
 * @return bool
 */
public function __construct($number, $battery_type=1)
{
	parent::__construct($number);
	switch($battery_type)
	{
		case 1:
		case 2:
		case 3:
			$this->battery_type = $battery_type;
			break;
		default:
			echo "Invalid battery type";
			return false;
			break; // i know it is not necessary...
	}
}
}

/**
* Cell phone
* 
* Same as wireless phone except that it can send text messages.
*/
class cell_phone extends wireless_phone
{
/**
 * Send text message
 * 
 * Sends a message. If $recipients can either be an array or an integer.
 *
 * @access public
 * @param int|array $recipients
 * @param str $message
 */
public function send_text_message($recipients, $message)
{
	if(is_array($recipients))
	{
		foreach($recipients as $recipient)
		{
			$this->send_message($recipient, $message);
		}
	}
	else {
		$this->send_message($recipients, $message);
	}
}

/**
 * Send message
 * 
 * Internal function to handle the sending of text messages
 *
 * @access private
 * @param int $recipient
 * @param str $message
 * @return bool
 */
private function send_message($recipient, $message)
{
	// stuff here
}
}
?>

 

You can also make objects that group functions together in "categories", e.g. error handling functions, session handling functions, etc.

Link to comment
Share on other sites

Classes are also useful for handling information that is all related.

 

That's why 99% of good PHP developers will make a MySQL class if they EVER need to manage a database in their scripts.  Why call a bunch of messy, unrelated functions, when you can just run:

$DB->connect('user', 'pass', 'db');
$DB->query("SQL QUERY");
while ($row = $DB->getRow()) {

}

Then you don't have to deal with a bunch of global delcarations, or passing the MySQL link identifier to each function.

Link to comment
Share on other sites

Well... it took a very long time for me to understand about a class, then after understanding i had a confusion about how to use it, and i tried to use classes in my projects than using functions, then i realised ... to say, all that can be done using a class can be done using a function but it will be very easy if you use a class for anything in a project. you will not be confused if you have lot of functions. you can create a detailed fuinction in a class. for example you want to create a form, there can be lot of forms in a project example, user registration, preference, entering the content and much more, now you can create a form with much customizable appearence, like length, styles etc... if you make the customization more detailed ... then there will be lot values you will need to pass, then when you write a function it wil more lengthy and it its a class.... you can make shorter !...  well .. i am not sure if you understood what i said..... :P....

 

My advice is.... if you say that you understand the concept of classes and objects... practice it .the more  you practice you will come to know how you exactly need to use a class. try to use a class instead of a functions.....

 

if you are not clear about a class ... read this article which i found to be quite simple to understand about the class...

 

http://www.phpbuilder.com/columns/rod19990601.php3?page=1

 

 

Jaikar

 

 

Link to comment
Share on other sites

I've been playing around with classes and objects over the weekend to practice more in OOP, and I came across a few things I'm unclear about.

 

Firstly, as its advised to normally set your variables to private/protected, these values would be returned by a method inside that class. Now, suppose I create an instance of that class, and it contains 3 private variables. Which would be the best way to pass these to another class? I would create a method, and return them in an array, though I'm not sure this is the best way. For example, suppose I had a class (User) and I wanted to pass its properties (FirstName, SecondName, E-mail etc..) to another class (Invoice) to send that person an email.

 

Secondly, suppose I had a class (Invoice) and a class (Product). I also have 2 other classes, Product_web and Product_hosting which extend Product. Product contains a public $MonthlyCost and $SetupCost variable. Now, in the Invoice class I create a method to pass products: loadProduct($Product). I create seperate instances for Product_web and Product_hosting and pass each to loadProduct(). I also have a method totalCosts() which calculates the total cost of all products. Here is the bit that confuses me. How would I calculate the total of all $MonthlyCosts and $SetupCosts? The way I did this was using this method in the Invoice class, to create a multidimensional array.

 

function loadProduct($product){

	$myKey = count($this->Products);
	$myKey++;

	foreach($product as $var => $value) {
		$this->Products[$myKey]["$var"] = $value;
    	            }
    	
}

 

Then in the totalCosts() method I would loop through the array. But really I only want the values $MonthlyCost and $SetupCost, instead of returning all properties of the Product.

 

Any ideas? I hope I explained this well :)

Link to comment
Share on other sites

Why not create a couple of methods (functions) in your product:

 

class product
{
  function monthly_cost()
  {
    return 55;
  }

  function setup_cost()
  {
    return 17.5;
  }

  function total_cost()
  {
    return $this->setup_cost() + $this->monthly_cost();
  }
}

$p = new product();
echo $p->monthly_cost();
echo $p->setup_cost();
echo $p->total_cost();

 

any help?

 

monk.e.boy

Link to comment
Share on other sites

For example, suppose I had a class (User) and I wanted to pass its properties (FirstName, SecondName, E-mail etc..) to another class (Invoice) to send that person an email.

 

Pass the user object into the invoice:

 

$u = new user( 'jeff' );

$i = new invoice();
$i->invoice_user( $u );

 

invoice_user would then access user methods, like $u->get_name().

 

or invoice could be a method in the user object, so then you could do:

 

foreach( $users as $user )
  $user->invoice();

 

 

monk.e.boy

Link to comment
Share on other sites

What I meant was I wanted the Invoice class to be able to get the total costs of all products. Suppose I pass several product objects, I'd like it to be able to hold those, and add them all together. The only way I can think of doing this is a multidimensional array (in the Invoice class) e.g. Product[$x]["$monthly_cost"], and to loop through $x to get the sum of the monthly cost of all products. In the example you gave, its just adding the monthly and setup cost of one product (one instance), where as I'd like to be able to pass several instances.

 

Why not create a couple of methods (functions) in your product:

 

class product
{
  function monthly_cost()
  {
    return 55;
  }

  function setup_cost()
  {
    return 17.5;
  }

  function total_cost()
  {
    return $this->setup_cost() + $this->monthly_cost();
  }
}

$p = new product();
echo $p->monthly_cost();
echo $p->setup_cost();
echo $p->total_cost();

 

Link to comment
Share on other sites

If I were to use an accessor method such as $u->get_name(), how could I return several values in that method?

 

As far as I know, you can do:

 

return $FirstName;

 

To return several values (FirstName, SecondName, E-mail) in the same method, is the only way to create an array and return that? It seems like a lot of methods if its just to return single properties.

 

For example, suppose I had a class (User) and I wanted to pass its properties (FirstName, SecondName, E-mail etc..) to another class (Invoice) to send that person an email.

 

Pass the user object into the invoice:

 

$u = new user( 'jeff' );

$i = new invoice();
$i->invoice_user( $u );

 

invoice_user would then access user methods, like $u->get_name().

 

or invoice could be a method in the user object, so then you could do:

 

foreach( $users as $user )
  $user->invoice();

 

 

monk.e.boy

Link to comment
Share on other sites

You can set properties inside that class for instance

 

<?php

class clClass {
        var $fname;
        var $lname;
        var $mname;

        function clClass () {
              // constructor
        }

        function get_name() {
               $this->fname = "First";
               $this->lname = "Last";
               $this->mname = "Middle";
        }
}

$clClass = new clClass();

$clClass->get_name();

$fullName = $clClass->fname . " " . $clClass->mname . " " . $clClass->lname;
print $fullName;
?>

 

That is one way to do it. The other way is the array.

Link to comment
Share on other sites

What I meant was I wanted the Invoice class to be able to get the total costs of all products.

 

I'd do this:

 

class order
{
  var $_products;
  function order()
  {
    $this->_products = array();
  }

  function add_product( $p )
  {
    $this->_products.push( $p );
  }

  function total()
  {
    $total = 0;
    foreach( $this->_products as $p )
      $total += $p.value();

    return $total;
  }
}

$my_order = new order();
$my_order.add_product( new book() );
$my_order.add_product( new dvd() );
$my_order->total();

 

This is a wrapper class, it wraps the generic array, and adds some specific stuff to make it a list of products. It also knows how to get the total value of all products. Similarly it could also do 'purchase' on all products, or 'remove all that cost > $100' etc.

 

Note, both book and dvd would need to provide a method called .value().

 

monk.e.boy

 

 

Link to comment
Share on other sites

<?php

class clClass {
        var $fname;
        var $lname;
        var $mname;

        function clClass () {
               $this->fname = "First";
               $this->lname = "Last";
               $this->mname = "Middle";
        }

        function get_name() {
               return $this->fname . " " . $this->mname . " " . $this->lname;
        }
}

$clClass = new clClass();
echo $clClass->get_name();

?>

 

Link to comment
Share on other sites

Thanks for that, I think I'm getting the hang of it now.

 

Looking back at what I originally did, the multidimensional array is quite messy!

 

The total() method in Order and the value() in Product makes a lot more sense. I suppose I could also call value($type) and call whichever $type I wanted e.g. setupCost or monthlyCost, and have that return it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.