Tag Archive for 'oop beginners'

Page 2 of 2

Easy Writer: Setup for Raspberry Pi PHP

RaspPHPFocus on writing PHP Code

In fiddling around with PHP on a Raspberry Pi running on a Debian Linux OS more or less directly from a terminal mode, I realized that the focus (in my case) was getting the Linux commands right and very little with actually writing PHP programs. Most queries about getting the setup right involved Linux system administration and not PHP programming.

This short post is for Raspberry Pi users (and perhaps Linux users in general), and it focuses on setting up your Raspberry Pi so that you can use default Raspberry Pi editors (LeafPad) and the File Manager to work with PHP programs. Once set up, you will find the process of creating server-side programs in PHP much easier with no need to use the  terminal editors after setting up your system.

Installing Apache and PHP

Because PHP is a server-side language, you will need both a server and PHP installed on your Raspberry Pi. Using the Root Terminal (Accessories → Root Terminal), enter the following line:

sudo apt-get install apache2 php5 libapache2-mod-php5

Press the Enter key and patiently wait until it’s completed the setup. Once done, you computer will have both a web server and PHP installed. To test whether installation was successful, open a browser from the main menu (Internet → NetSurf Web Browser) and enter the following:

  http://localhost/

If everything works, you will see the message shown in Figure 1 on the right:

Figure 1: Default Web Page

Figure 1: Default Web Page

This location (http://localhost) is the root for your Web pages—PHP and any other Web page you decide to put on your Raspberry Pi Apache server. The name of the file is index.html. On your Raspberry Pi, in the Linux file system, the address is:

  /var/www/

Open the File Manager (Accessories → File Manager) and in the window where you see /home/pi enter /var/www. You will now be able to see the icon for the html file that was automatically created when you installed the Apache server.
Continue reading ‘Easy Writer: Setup for Raspberry Pi PHP’

Share

OOP PHP III: Properties and Variables

oop3From Variable to Class Property

All classes in all programming languages are made up of two fundamental elements, 1) Methods and 2) Properties. In this installation of learning OOP in PHP, I want to look at properties.

To understand properties in a PHP class, it’s important to understand (at this stage) that we’re dealing with variables. Variables inside of a class can act as properties of that class or properties of a method within a class. In OOP, we speak of visibility of variables/properties. You will find an earlier post on this blog that explains private variables in detail, and future posts delve into visibility in greater detail. For now variables in PHP (and virtually every other programming language) have two basic types:

  • local
  • global

Generally speaking any variable declared outside of a function in a sequential or procedural listing is global, and any variable declared inside of a function is local. The same is true to some extent in OOP programming, but variables (or properties) require a different sense. Take a look at the video, and you’ll see the basics of variables within classes.

The video touches on the most fundamental aspects of variables and properties. However, as every PHP programmer knows, there’s no substitute for some clear practical OOP PHP code. The following examples show several different aspects of creating and using variables and properties.

All of these examples use a Client->Request->Class model. The first is similar to the one in the video except it has a client make the request:
Client 1
Client1

<?php
//Client1.php
include_once('OneProp.php');
class Client1
{
 
        public function __construct()
        {
            //$oneProp is a local variable
            $oneProp = new OneProp();
            echo $oneProp->showProperties();
        }
}
//$worker is a global variable in this program
$worker = new Client1();
?>

OneProp

<?php
//OneProp.php
class OneProp
{
        private $magicWord;
 
        public function showProperties()
        {
            $this->magicWord = "<h1> Alacazam! </h1>";
            return  $this->magicWord;  
        }
}
?>

More Properties and a Little JavaScript inside PHP Class

This last example is a little more involved. One of the properties is assigned an entire Web page using heredoc. Two more properties serve as labels and instructions. Here we use a little JavaScript, and the JavaScript event handler (onClick) uses the this statement and property reference using a dot:

this.src

Because the JavaScript is part of a heredoc string in a PHP property ($this->document), PHP does not attempt to execute the JavaScript or find an error in its format. (In other words it doesn’t throw an error when this.src appears instead of $this->src is in the JavaScript listing.)

Client2

<?php
include_once('ImageSwap.php');
class Client2
{
        private $light;
        public function __construct()
        {
            $light = new ImageSwap();
        }
}
$worker = new Client2();
?>

ImageSwap

<?php
//ImageSwap.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
class ImageSwap
{
    private $document;
    private $turnOff;
    private $howTo;
 
    public function __construct()
    {
        $this->document = <<<LIGHTSWITCH
        <!doctype html>
        <html>
        <head>
        <meta charset="UTF-8">
        <script>
            var onImg= "on.jpg";
            var offImg= "off.jpg";
        </script>
        <title>Light Switch</title>
        </head>
        <body>
        <img src="on.jpg" onclick="this.src = this.src == offImg ? onImg : offImg;"/>
        </body>
        </html>
LIGHTSWITCH;
        $this->turnOff = "<h3>Turn off the light!</h3>";
        $this->howTo = "<h4>(Just click the image!)</h4>";
 
        echo $this->turnOff;
        echo $this->document;
        echo $this->howTo;    
    }
}
?>

To run this, you’ll need to download the following two graphic files:
onoff

Put the two graphic files into the same directory as the classes you’ll be using. Notice how the three different properties in the ImageSwap class are employed. Also note that in the two Client classes, the $worker variable (not a property because it does not belong to a class) is assigned an object. To download the two graphic files, just right click to download them and then move them to the same directory (folder) with your ImageSwap.php file. In the next installment of OOP PHP, we’ll look at the visibility that properties and methods can have and how to use them.

Share

OOP PHP II: Arithmetic Operators and Communicating Objects

oop2Object Communication

Hope to get up the final CMS post by tomorrow (July 9), but in the meantime, I wanted to get this next OOP PHP post up. One of the essential elements of OOP in any language is that it is written as communication between objects. Design patterns are simply ways to help arrange that communication process so that things don’t get tangled up. Sequential and procedural programming are never far from the abyss of tangle, and as long as the scripts or code blocks are short, you can get away with it. But for both the sequential and procedural programmers, spaghetti code is lurking like a vulture on the programmer’s shoulder. So in learning OOP, one of the very first things to understand and use is how objects communicate with one another.

In learning PHP or any other language, one of the first things to understand is how to use the arithmetic operators. The six such operators in PHP are – (negation) + (add), – subtract, * (multiply), / (divide) and % (modulus). Usually the next step is to learn about precedence and how to use parentheses to re-order precedence. However, other than a quick mention that modulus refers to finding the remainder in division, there’s usually not a lot of discussion about it. However, for programmers there’s a huge number of uses of modulus. Check out some articles on modular arithmetic. (You’ll never have problems working with 12-hour clocks again using $value % 12.)

Some examples

I put together some simple code examples of using object communication and math operators. It might help to have them handy when viewing the video. Each listing below should be saved as a separate file with the .php extension.

Call to single method object

Client.php

<?php
//Client.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('EZMath.php');
 
class Client
{
    public function __construct()
    {
       $math = new EZMath();
       echo $math->doAdd(7, 22);    
    }  
}
$worker = new Client();
?>

EZMath.php

<?php
//EZMath.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
 
class EZMath
{ 
   public function doAdd($alpha,$beta)
   {
        return $alpha + $beta;
   }  
}
?>

Call to multiple method object

Client1.php

<?php
//Client1.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('EZMath1.php');
 
class Client1
{
    public function __construct()
    {
       $cr = "<br />";
       //Enter your own birth year
       $bday = 1985;
 
       $math = new EZMath1();
       echo $math->doNegate(44) . $cr;
       echo $math->doAdd(12, 26) . $cr;
       echo $math->doSubtract(2013, $bday) . " years old $cr";
       echo $math->doMultiply(12, 26) . $cr;
       echo $math->doDivide(500, 25) . $cr;
       echo $math->doModulus(14, 12) . " pm o'clock $cr";  
    }
 
}
 
$worker = new Client1();
 
?>

EZMath1.php

<?php
//EZMath1.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
 
class EZMath1
{
 
   public function doNegate($alpha)
   {
        $alpha = -$alpha;
        return $alpha;
   }
 
   public function doAdd($alpha,$beta)
   {
        return $alpha + $beta;
   }
 
   public function doSubtract($alpha,$beta)
   {
        return $alpha - $beta;
   }
 
   public function doMultiply($alpha,$beta)
   {
        return $alpha * $beta;
   }
 
   public function doDivide($alpha,$beta)
   {
        return $alpha / $beta;
   }
 
   public function doModulus($alpha,$beta)
   {
        return $alpha % $beta;
   }
}
 
?>

Coin Flip Game Using Modular Arithmetic

CoinClient.php

<?php
//CoinClient.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('CoinFlip.php');
 
class CoinClient
{
    public function __construct()
    {
       //Instantiates instance
       $flipper = new CoinFlip();
       //Makes a request
       echo $flipper->doFlip();   
    }   
}
$worker = new CoinClient();
?>

CoinFlip.php

<?php
//CoinFlip.php
class CoinFlip
{
   public function doFlip()
   {
    //rand is built-in PHP method for generating random number
    $coin = rand(1,200);
    //Uses modulo operator (%) to generate 1 or 0
    //When you divide by 2 the remainder is always 1 or 0
    //tests for true (1) or false (0)
    $results = $coin % 2;
    if($results)
    {
        $flip="Heads";
    }
    else
    {
        $flip = "Tails";   
    }
    return $flip;
   }
}
 
?>

You can play around with these examples, and you should get the fundamental idea of objects communicating with one another. See if you can create some of your own.

Share