Current location: Hot Scripts Forums » Programming Languages » PHP » Can someone explain this to me?


Can someone explain this to me?

Reply
  #1 (permalink)  
Old 09-10-11, 12:47 AM
phphelpme phphelpme is offline
Newbie Coder
 
Join Date: Jul 2010
Posts: 85
Thanks: 10
Thanked 0 Times in 0 Posts
Can someone explain this to me?

ok well i got this new book , about social networking and it has alot of code in it and i am having a hard time understanding it , can any one explain it to me line by line? here is the code( only first part of it , if i understand this one i will under stand all the other scripts)

PHP Code:

<?php


class Registry {
    
    
/**
     * Array of objects
     */
    
private $objects;
    
    
/**
     * Array of settings
     */
    
private $settings;
    
    public function 
__construct() {
    }
    
    
/**
     * Create a new object and store it in the registry
     * @param String $object the object file prefix
     * @param String $key pair for the object
     * @return void
     */
    
public function createAndStoreObject$object$key )
    {
        require_once( 
$object '.class.php' );
        
$this->objects$key ] = new $object$this );
    }
    
    
/**
     * Get an object from the registries store
     * @param String $key the objects array key
     * @return Object
     */
    
public function getObject$key )
    {
        return 
$this->objects$key ];
    }
    
    
/**
     * Store Setting
     * @param String $setting the setting data
     * @param String $key the key pair for the settings array
     * @return void
     */
    
public function storeSetting$setting$key )
    {
        
$this->settings$key ] = $setting;
    }
    
    
/**
     * Get a setting from the registries store
     * @param String $key the settings array key
     * @return String the setting data
     */
    
public function getSetting$key )
    {
        return 
$this->settings$key ];
    }
}

?>
Reply With Quote
  #2 (permalink)  
Old 09-10-11, 05:55 PM
kfurlong's Avatar
kfurlong kfurlong is offline
Wannabe Coder
 
Join Date: Oct 2010
Posts: 150
Thanks: 6
Thanked 20 Times in 20 Posts
Okay, here we go...

Im not the best with classes, so maybe someone can explain to you better, but here is my go at it... It looks like this code is just trying to show you how to use classes, and isnt an actual example. You have some pretty good comments in there already. Ill try to elaborate.

PHP Code:


<?php


// THis is creating a class called Registry. 
class Registry {

    

    
/**

     * Array of objects - This is exactly what it says, it is defining a variable called Objects, and your comment is telling us this is going to be an array. (which is true when we look further down in the code)

     */

    
private $objects;

    

    
/**

     * Array of settings - Same as above. This is going to be some type of user settings. This is not a standard, its just the variable name, it could be anything $user_settings... whatever you want it to be. Same with $objects its just the name. not a standard coding term.

     */

    
private $settings;

    
// This function gets ran when you create a new instance of the Registry Class. Every time you insert the code: new Registry;  This function gets ran. It is basically an initialization routine. So if you want to preload the $settings array with certain settings, it would probably be done here.
    
public function __construct() {

    }

    

    
/**

     * Create a new object and store it in the registry

     * @param String $object the object file prefix

     * @param String $key pair for the object

     * @return void

     */
// Okay, an object is pretty much part of the class. This is a little confusing, but bear with me. 
// When you create a class variable like so VARIABLE = new CLASS; you are creating an OBJECT variable. I think what your book is trying to show you here is using a class inside of a class. Soooooo with this backgound lets keep going and it might make more sense.
//This line is creating a function inside of the class which will basically add another class object into the Registry class's $objects variable array. 
    
public function createAndStoreObject$object$key )

    {
//this line grabs the object from class.php file so thatt you can use it in this file/class
        
require_once( $object '.class.php' );
//$this is a standard variable in php. it is the variable that refers to whatever class you are in (in this case it is the Registry class)  the arrow (->) is an operator? i dont know the exact term for it, but it means you are further defining the part of the class you want to work with, if you picture a tree diagram the class name is on top (in this case Registry and then under it (its children) would be $objects, $settings...etc  So you are saying in THIS class, the OBJECTS VARIABLE with the key of the array being $key  set it equal to a new instance of $object (defined from when you run this function which is "createAndStoreObject" and $object is a parameter.
        
$this->objects$key ] = new $object$this );

    }

    

    
/**

     * Get an object from the registries store

     * @param String $key the objects array key

     * @return Object

     */
//This line is creating a new function inside of the class which will return a value from the objects array with a key of whatever you put in the parameters portion when calling the function.
    
public function getObject$key ){
//This will return the value. in THIS class in the OBJECTS array with a key of KEY 
        
return $this->objects$key ];

    }

    

    
/**

     * Store Setting

     * @param String $setting the setting data

     * @param String $key the key pair for the settings array

     * @return void

     */
//This is basically the same this as the object functions except with the setting variable instead. The big difference here is that the object functions are pertinent to objects (classes within classes) where the setting array is working with strings or numbers.( something other than objects)... that is confusing and hard to explain, but I hope it makes sense
//So here we are creating a function storeSetting that will store $setting as the value into this classes $setting array with a key of $key so an example would be storeSetting("red",'BackColor'); would create or change the $setting[BackColor] = 'red'; in normal non-class coding equivalent
    
public function storeSetting$setting$key )

    {
// I pretty much explained this above. It goes through the parent/child "tree" relationship. THIS CLASS... SETTINGS variable array ... with a key of KEY. and set its value to be $setting (defined as a parameter of the function storeSetting.
        
$this->settings$key ] = $setting;

    }

    

    
/**

     * Get a setting from the registries store

     * @param String $key the settings array key

     * @return String the setting data

     */
//getSetting is a function that will return the value of a key in the settings array within the THIS class. THe line below defines the function with one parameter refered to as $key
    
public function getSetting$key )

    {
//This line will return the value (going through the parent child tree relationship) THIS CLASS in the SETTINGS variable array with a key of $key (which is defined as a parameter of the function getSetting) so an normal equivalent would be $backColor  = getSetting('BackColor'); would return red. Obviously you have to use the class syntax for it (create the instance of the class and what not but I think this should give you an idea.
        
return $this->settings$key ];

    }

}



?>

Im sorry if its really confusing, but this code is just setting up the class, if you have the application of the class it would be easier to folllow, but here is what my example would be:

PHP Code:

$instance = new Registry;
$instance->storeSetting('red','BackColor');
echo
"Your background color is: "$instance->getSetting('BackColor'); 
If you are still confused about a certain line ask more questions. I hope it helps at least a little bit.
Reply With Quote
  #3 (permalink)  
Old 09-11-11, 12:36 AM
phphelpme phphelpme is offline
Newbie Coder
 
Join Date: Jul 2010
Posts: 85
Thanks: 10
Thanked 0 Times in 0 Posts
THank you

ok so here is the msqldb.class.php file , so would this be connected at all to the other script?
PHP Code:

class Mysqldb {

    
    
/**
     * Allows multiple database connections
     * each connection is stored as an element in the array, and the active connection is maintained in a variable (see below)
     */
    
private $connections = array();
    
    
/**
     * Tells the DB object which connection to use
     * setActiveConnection($id) allows us to change this
     */
    
private $activeConnection 0;
    
    
/**
     * Queries which have been executed and the results cached for later, primarily for use within the template engine
     */
    
private $queryCache = array();
    
    
/**
     * Data which has been prepared and then cached for later usage, primarily within the template engine
     */
    
private $dataCache = array();
    
    
/**
     * Number of queries made during execution process
     */
    
private $queryCounter 0;
    
    
/**
     * Record of the last query
     */
    
private $last;
    
    
/**
     * Reference to the registry object
     */
    
private $registry;
    
    
/**
     * Construct our database object
     */
    
public function __constructRegistry $registry 
    {
        
$this->registry $registry;    
    }
    
    
/**
     * Create a new database connection
     * @param String database hostname
     * @param String database username
     * @param String database password
     * @param String database we are using
     * @return int the id of the new connection
     */
    
public function newConnection$host$user$password$database )
    {
        
$this->connections[] = new mysqli$host$user$password$database );
        
$connection_id count$this->connections )-1;
        if( 
mysqli_connect_errno() )
        {
            
trigger_error('Error connecting to host. '.$this->connections[$connection_id]->errorE_USER_ERROR);
        }     

        
        return 
$connection_id;
    }
    
    
/**
     * Close the active connection
     * @return void
     */
    
public function closeConnection()
    {
        
$this->connections[$this->activeConnection]->close();
    }
    
    
/**
     * Change which database connection is actively used for the next operation
     * @param int the new connection id
     * @return void
     */
    
public function setActiveConnectionint $new )
    {
        
$this->activeConnection $new;
    }
    
    
/**
     * Store a query in the query cache for processing later
     * @param String the query string
     * @return the pointed to the query in the cache
     */
    
public function cacheQuery$queryStr )
    {
        if( !
$result $this->connections[$this->activeConnection]->query$queryStr ) )
        {
            
trigger_error('Error executing and caching query: '.$this->connections[$this->activeConnection]->errorE_USER_ERROR);
            return -
1;
        }
        else
        {
            
$this->queryCache[] = $result;
            return 
count($this->queryCache)-1;
        }
    }
    
    
/**
     * Get the number of rows from the cache
     * @param int the query cache pointer
     * @return int the number of rows
     */
    
public function numRowsFromCache$cache_id )
    {
        return 
$this->queryCache[$cache_id]->num_rows;    
    }
    
    
/**
     * Get the rows from a cached query
     * @param int the query cache pointer
     * @return array the row
     */
    
public function resultsFromCache$cache_id )
    {
        return 
$this->queryCache[$cache_id]->fetch_array(MYSQLI_ASSOC);
    }
    
    
/**
     * Store some data in a cache for later
     * @param array the data
     * @return int the pointed to the array in the data cache
     */
    
public function cacheData$data )
    {
        
$this->dataCache[] = $data;
        return 
count$this->dataCache )-1;
    }
    
    
/**
     * Get data from the data cache
     * @param int data cache pointed
     * @return array the data
     */
    
public function dataFromCache$cache_id )
    {
        return 
$this->dataCache[$cache_id];
    }
    
    
/**
     * Delete records from the database
     * @param String the table to remove rows from
     * @param String the condition for which rows are to be removed
     * @param int the number of rows to be removed
     * @return void
     */
    
public function deleteRecords$table$condition$limit )
    {
        
$limit = ( $limit == '' ) ? '' ' LIMIT ' $limit;
        
$delete "DELETE FROM {$table} WHERE {$condition} {$limit}";
        
$this->executeQuery$delete );
    }
    
    
/**
     * Update records in the database
     * @param String the table
     * @param array of changes field => value
     * @param String the condition
     * @return bool
     */
    
public function updateRecords$table$changes$condition )
    {
        
$update "UPDATE " $table " SET ";
        foreach( 
$changes as $field => $value )
        {
            
$update .= "`" $field "`='{$value}',";
        }
               
        
// remove our trailing ,
        
$update substr($update0, -1);
        if( 
$condition != '' )
        {
            
$update .= "WHERE " $condition;
        }
        
$this->executeQuery$update );
        
        return 
true;
        
    }
    
    
/**
     * Insert records into the database
     * @param String the database table
     * @param array data to insert field => value
     * @return bool
     */
    
public function insertRecords$table$data )
    {
        
// setup some variables for fields and values
        
$fields  "";
        
$values "";
        
        
// populate them
        
foreach ($data as $f => $v)
        {
            
            
$fields  .= "`$f`,";
            
$values .= ( is_numeric$v ) && ( intval$v ) == $v ) ) ? $v."," "'$v',";
        
        }
        
        
// remove our trailing ,
        
$fields substr($fields0, -1);
        
// remove our trailing ,
        
$values substr($values0, -1);
        
        
$insert "INSERT INTO $table ({$fields}) VALUES({$values})";
        
//echo $insert;
        
$this->executeQuery$insert );
        return 
true;
    }
    
    public function 
lastInsertID()
    {
        return 
$this->connections$this->activeConnection]->insert_id;
    }
    
    
/**
     * Execute a query string
     * @param String the query
     * @return void
     */
    
public function executeQuery$queryStr )
    {
        if( !
$result $this->connections[$this->activeConnection]->query$queryStr ) )
        {
            
trigger_error('Error executing query: ' $queryStr .' - '.$this->connections[$this->activeConnection]->errorE_USER_ERROR);
        }
        else
        {
            
$this->last $result;
        }
        
    }
    
    
/**
     * Get the rows from the most recently executed query, excluding cached queries
     * @return array 
     */
    
public function getRows()
    {
        return 
$this->last->fetch_array(MYSQLI_ASSOC);
    }
    
    public function 
numRows()
    {
        return 
$this->last->num_rows;
    }
    
    
/**
     * Gets the number of affected rows from the previous query
     * @return int the number of affected rows
     */
    
public function affectedRows()
    {
        return 
$this->last->affected_rows;
    }
    
    
/**
     * Sanitize data
     * @param String the data to be sanitized
     * @return String the sanitized data
     */
    
public function sanitizeData$value )
    {
        
// Stripslashes 
        
if ( get_magic_quotes_gpc() ) 
        { 
            
$value stripslashes $value ); 
        } 
        
        
// Quote value
        
if ( version_comparephpversion(), "4.3.0" ) == "-1" 
        {
            
$value $this->connections[$this->activeConnection]->escape_string$value );
        } 
        else 
        {
            
$value $this->connections[$this->activeConnection]->real_escape_string$value );
        }
        return 
$value;
    }
    
    
/**
     * Deconstruct the object
     * close all of the database connections
     */
    
public function __deconstruct()
    {
        foreach( 
$this->connections as $connection )
        {
            
$connection->close();
        }
    }

AND THEN HERE IS THE page.class.php
PHP Code:

class page {



    
// page elements
    
    // page title
    
private $title '';
    
// template tags
    
private $tags = array();
    
// tags which should be processed after the page has been parsed
    // reason: what if there are template tags within the database content, we must parse the page, then parse it again for post parse tags
    
private $postParseTags = array();
    
// template bits
    
private $bits = array();
    
// the page content
    
private $content "";
    private 
$apd =  array();
    
    
/**
     * Create our page object
     */
    
function __constructRegistry $registry 
    {
        
$this->registry $registry;
    }
    
    
/**
     * Get the page title from the page
     * @return String
     */
    
public function getTitle()
    {
        return 
$this->title;
    }
    
    
/**
     * Set the page title
     * @param String $title the page title
     * @return void
     */
    
public function setTitle$title )
    {
        
$this->title $title;
    }
    
    
/**
     * Set the page content
     * @param String $content the page content
     * @return void
     */
    
public function setContent$content )
    {
        
$this->content $content;
    }
    
    
/**
     * Add a template tag, and its replacement value/data to the page
     * @param String $key the key to store within the tags array
     * @param String $data the replacement data (may also be an array)
     * @return void
     */
    
public function addTag$key$data )
    {
        
$this->tags[$key] = $data;
    }
    
    public function 
removeTag$key )
    {
        unset( 
$this->tags[$key] );
    } 
    
    
/**
     * Get tags associated with the page
     * @return void
     */
    
public function getTags()
    {
        return 
$this->tags;
    }
    
    
/**
     * Add post parse tags: as per adding tags
     * @param String $key the key to store within the array
     * @param String $data the replacement data
     * @return void
     */
    
public function addPPTag$key$data )
    {
        
$this->postParseTags[$key] = $data;
    }
    
    
/**
     * Get tags to be parsed after the first batch have been parsed
     * @return array
     */
    
public function getPPTags()
    {
        return 
$this->postParseTags;
    }
    
    
/**
     * Add a template bit to the page, doesnt actually add the content just yet
     * @param String the tag where the template is added
     * @param String the template file name
     * @return void
     */
    
public function addTemplateBit$tag$bit )
    {
        
$this->bits$tag ] = $bit;
    }
    
    
/**
     * Adds additional parsing data
     * A.P.D is used in parsing loops.  We may want to have an extra bit of data depending on on iterations value
     * for example on a form list, we may want a specific item to be "selected"
     * @param String block the condition applies to
     * @param String tag within the block the condition applies to
     * @param String condition : what the tag must equal
     * @param String extratag : if the tag value = condition then we have an extra tag called extratag
     * @param String data : if the tag value = condition then extra tag is replaced with this value
     */
    
public function addAdditionalParsingData($block$tag$condition$extratag$data)
    {
        
$this->apd[$block] = array($tag => array('condition' => $condition'tag' => $extratag'data' => $data));
    }
    
    
/**
     * Get the template bits to be entered into the page
     * @return array the array of template tags and template file names
     */
    
public function getBits()
    {
        return 
$this->bits;
    }
    
    public function 
getAdditionalParsingData()
    {
        return 
$this->apd;
    }
    
    
/**
     * Gets a chunk of page content
     * @param String the tag wrapping the block ( <!-- START tag --> block <!-- END tag --> )
     * @return String the block of content
     */
    
public function getBlock$tag )
    {
        
//echo $tag;
        
preg_match ('#<!-- START '$tag ' -->(.+?)<!-- END '$tag ' -->#si'$this->content$tor);    
        
$tor str_replace ('<!-- START '$tag ' -->'""$tor[0]);
        
$tor str_replace ('<!-- END '  $tag ' -->'""$tor);
        
        return 
$tor;
    }
    
    public function 
getContent()
    {
        return 
$this->content;
    }
    
    public function 
getContentToPrint()
    {
        
$this->content preg_replace ('#{form_(.+?)}#si'''$this->content);    
        
$this->content preg_replace ('#{nbd_(.+?)}#si'''$this->content);    
        
$this->content str_replace('</body>''<!-- Generated by our Fantastic Social Netowk -->
</body>'
$this->content );
        return 
$this->content;
    }
  
}
?> 

Last edited by phphelpme; 09-11-11 at 12:50 AM.
Reply With Quote
  #4 (permalink)  
Old 09-11-11, 01:25 PM
kfurlong's Avatar
kfurlong kfurlong is offline
Wannabe Coder
 
Join Date: Oct 2010
Posts: 150
Thanks: 6
Thanked 20 Times in 20 Posts
hmmm im not sure what you are asking

the class files only need to be included on the pages where the class is used.

I think.... Im not sure, but I think... That when you use the classes it wont carry it over as the user navigates through your site, because the server opens the php file reads it and then closes it ultra fast. I think that is why IMO classes are pretty much pointless in php. Ya, it will get the job done, ya it is organized for big projects and easy to understand the code written, but I think that code can be done just as well without classes. Now for something like C/C++/C# or ActionScript, I can see how it can be very useful because you can create more instances of the same thing over and over again (like enemies in a game), but as far as I have seen, I have not needed classes too much in php... Sorry for my rant.
Reply With Quote
The Following User Says Thank You to kfurlong For This Useful Post:
phphelpme (09-12-11)
Reply

Bookmarks

Tags
javascript, php, php and mysql, php help


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Could someone help me explain to understand what this script is doing? sbuk JavaScript 1 11-02-10 09:27 AM
Can you explain to me..?? Miss_H_Roshan ASP.NET 1 04-13-09 06:54 PM
Help Explain this... airprince Visual Basic 2 05-10-06 09:30 AM
Ok, ill try and explain this... Iruga Script Requests 2 08-08-04 11:40 AM
Hi, can someone explain this error? onetimeuse PHP 5 07-27-03 09:21 AM


All times are GMT -5. The time now is 08:49 AM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.