PHP – Use

From a follow on from my previous post about namespace, when you want to use another name, shorter than the actual namespace of the namespace you are able to use “use”. Probably best to show in code

include "codingfriends.php";
 
use codingfriends as cf;
 
echo cf\sayHello()."<br/>";

the codingfriends.php file is

<?php
namespace codingfriends;
 
function sayHello()
{
    echo "Say hello from codingfriends.";    
}
 
function sayHelloFromSub()
{
    echo sub\sayHello();
}
?>

so that the “use” will alter the namespace of codingfriends to cf instead so that you are able to call codingfriends as cf, so when

echo cf\sayHello()."<br/>";

is called it will call the codingfriends\sayHello() function.

PHP – namespace

Namespace‘ing is a great way of splitting functions / classes into different spaces that could have the same name but do not cause issues. This is great if you are trying to combine different projects together that many have the same function names and you want to call different projects code functions without having to worry that you are calling the wrong function.

For example if you have a file called codingfriends.php

<?php
namespace codingfriends;
 
function sayHello()
{
    echo "Say hello from codingfriends.";    
}
 
function sayHelloFromSub()
{
    echo sub\sayHello();
}
?>

and another file called codingfriendssub.php

<?php
namespace codingfriends\sub;
 
function sayHello()
{
    echo "Say hello from codingfriends sub module";    
}
?>

and then have the index.php file

 
<?
include "codingfriends.php";
include "codingfriends.sub.php";
 
echo codingfriends\sayHello()."<br/>"; // calling the codingfriends namespace
echo codingfriends\sub\sayHello()."<br/>"; // call the codingfriends sub namespace
echo codingfriends\sayHelloFromSub()."<br/>"; // calling the sub namespace quicker.
?>

then the first two lines include the two different name spaces and you are able to call the same function names without having to worry that you are calling the wrong function.

echo codingfriends\sayHello()."<br/>"; // calling the codingfriends namespace

will call the sayHello() from within the namespace codingfriends

echo codingfriends\sub\sayHello()."<br/>"; // call the codingfriends sub namespace

will call the namespace codingfriendssub sayHello function and the best thing is is if you are within a namespace and want to call a sub namespace within your namespace (it is like a tree with roots) you are able to do

    echo sub\sayHello();

from within the namespace codingfriends, it will find the codingfriends\sub namespace and then call the sayHello() function within that namespace.

The output would be for the index.php file

Say hello from codingfriends.
Say hello from codingfriends sub module
Say hello from codingfriends sub module

Google python code, string2.py

As from the previous post, I am doing the google’s python class code and if any one comes up different solutions to the googles version or mine, please post. So here is the string2.py solutions from me.

Verbing, needs to check for string over 3 and then only compare the last 3 characters for ‘ing’

# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(s):
  # +++your code here+++
  if len(s) < 3:
     return s
  elif (s[-3:] =='ing'):
     return s + 'ly'
  else:
     return s + 'ing'

Not bad, find the ‘not’ and ‘bad’, if bad after not then replace.

# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
  # +++your code here+++
  notV = s.find('not')
  badV = s.find('bad')
  if (badV > notV):
     return s[:notV] + 'good' + s[(badV+3):]
  return s

Font back, here we needed the modulus function to find out the reminder of a division.

# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
  # +++your code here+++
  aV = len(a)/2+(len(a)%2)
  bV = len(b)/2+(len(b)%2)
  return a[:aV]+b[:bV]+a[aV:]+b[bV:]

Google python code

After been talking with some friends, they said about putting some of the google code from there classes online encase other people come up with any other versions. So from the first of the classes that they was talking about was Python , so here is my code for these, may be other people may be doing and come up with different code ?

For first string1.py test there is 4 functions that you have code up and in order from the source code.

Donut, as from the below you just need do a compare on the parameter in.

# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
  # +++your code here+++
  if count >= 10:
     return 'Number of donuts: many'
  return 'Number of donuts: ' + str(count)

Both end, it is string manipulation and returning part of the string if longer enough.

# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
  # +++your code here+++
  if len(s) < 2:
    return ''
  return s[:2] + s[-2:]

Fix start, replace the characters within the string with a * that the same as the first character, so just need to concatenate the first character with the rest of the characters with any replaced 🙂

# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
  # +++your code here+++
  return s[0] + s[1:].replace(s[0],'*')

Mix up, change the first 2 characters from the two parameters around.

# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
#   'mix', pod' -> 'pox mid'
#   'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
  # +++your code here+++
  return b[:2]+a[2:]+' '+a[:2]+b[2:]

Final and auto load a class

To include a class within many languages you have to define it at the top and then off you go with programming with using that class. Well within PHP you can use the __autoload function that is called when you try to create a new instance of a class.

function __autoload($class_name) 
{
	include "classes/".$class_name.".php";
}

this __autoload function above takes a parameter as the class name to load and then within the code it will try and load that class with how ever you want to, in this case I have placed the classes within the directory called classes and under there classname.php filename.

So if you try to load the class

$newclass = new basic();

it will look within the classes directory for the file basic.php for the autoload function above, you can alter it to load from where ever and how ever you want to.

The next part of this post is about the keyword ‘final’, the final keyword means that it is final so if you try and extend that class and extend the function that has been declared as final this will cause php interpretor to fail due to syntax error with something similar to

Fatal error: Cannot override final method class_name::function_name()

For an example here is two classes one is called basic and the other is called extendbasic, where the basic class has the final function within it

class basic
{
	public function sayHello()
	{
		echo "<br/>".get_class($this) . " : Hello";
	}
 
	final public function sayGoodbye()
	{
		echo "<br/>".get_class($this) . " : Goodbye";
	}
}

and here is the extendclass

class extendbasic extends basic
{
	public function sayHello()
	{
		echo "<br/>".get_class($this). " : the newer hello!!";	
		parent::sayHello();
	}
        // this will cause the php engine to fail!!!!!. because it is trying to over load the function sayGoogbye which has been declared as final
/*	public function sayGoodbye()
	{
		echo "I should not get here!!";
	}*/
}

Here is some code to call them both which they have been placed within a directory called ‘classes’

function __autoload($class_name) 
{
	include "classes/".$class_name.".php";
}
 
$basicClass = new basic();
$basicClass->sayHello();
$basicClass->sayGoodbye();
$basicClass = new extendbasic();
$basicClass->sayHello();
$basicClass->sayGoodbye();

and the output would be

basic : Hello
basic : Goodbye
extendbasic : the newer hello!!
extendbasic : Hello
extendbasic : Goodbye

I am calling the parent function from within the extendbasic class sayHello function.

Ckeditor – not allow posting of images from the local harddrive

Within the CKEditor you can also add on to the prototypes that allow more control of what is allowed on your website.

Sometimes you do not want to allow the user to copy and paste local files to the CKEditor so this is what I done to remove the file:// from within the img tag within the copy and paste with using the CKEditor htmlDataProcessor group of functions, in this case the ‘toHtml’ function which is called when the user pastes any content into the CKEditor window. All I am doing it using the regular expression to search for the <img src=”file .. and replace with a <mg tag> which when they double click on that it will open the CKEditor’s image browser (which you can include a upload part to it as well 🙂 )

CKEDITOR.htmlDataProcessor.prototype.toHtml = function( data, fixForBody )
  {
    return data.replace(/\<img src=\"file:([^\>])*\>/ig,"<img title=\"Please use the Media/Image uploader because can not show files on your harddrive\" alt=\"Please use the Media/Image uploader because can not show files on your harddrive\"/>");
}

It was very helpful for me.

Classes

Since Python is a object oriented programming language then you can use things like classes to define a object, a class is a bunch of methods that act on the data that is stored within the class itself. You can store data within the class, but unlike c++/java/c# etc, there is no private/public/protected, everything is public accessible.

In the example below, the class constructor is called (__init__ method) and the first parameter is the class object itself, which is why it is there and for many reasons why it is called self as a variable name.

 
#  self means the object itself.
 
class mysimpleclass :
        __myvar = 0
        def __init__(self,value = 0) :
                self.__myvar = value
 
        def printValue(self) :
                print self.__myvar
 
simple = mysimpleclass(5)
simple.printValue()

the printValue method just does that, it will print the value that is sorted within the class object and here is the output

5

if you did not put in the self in the example above for printing out the class object variable __myvar as below

class mysimpleclass ....
       ....
       def printValue() :
            print __myvar

the error would be

NameError: global name '_mysimpleclass__myvar' is not defined

because the interrupter is looking for a global variable and not a variable attached to that object.