Archive

Posts Tagged ‘php’

Know PHP methods visibility (public, protected, private)

October 24, 2013 No comments

When coding in Object Oriented PHP, sometimes we would like to know the visibility of certain methods. For example, we are using an instance of an unknown class in compile-time (or coding time) with its name in a variable just like:

1
2
3
4
5
<?php
  $class = (isset($_GET['class']))?$_GET['class']:false;
  if ($class)
    $myObject = new $class;
?>

So, if we are going to call any method, we should know its visibility first. Another example, could be when we are checking the visibility in a base class. A subclass (“Heir”) of “Base” was instanced, and some methods of Base are going to call methods of Heir, so Base must know if they can be called.

Let’s check the visibility with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
function methodType($class, $method)
{
  try
    {
      $method = new ReflectionMethod($class, $method);
     
      if ($method->isPrivate())
    return 'private';
      elseif ($method->isProtected())
    return 'protected';
      elseif ($method->isPublic())
    return 'public';
    }
  catch (Exception $e)
    {
      return 'error';
    }
}

class MyClass
{
  function __construct()
  {
  }

  private function myPrivate()
  {
    echo "shhh... this is private\n";
  }

  public function myPublic()
  {
    echo "Hello everybody!!\n";
  }

  protected function myProtected()
  {
    echo "Protected method!!\n";
  }

}

$myclass = new MyClass();

echo 'myPrivate: '.methodType($myclass, 'myPrivate')."\n";
echo 'myPublic: '.methodType($myclass, 'myPublic')."\n";
echo 'myProtected: '.methodType($myclass, 'myProtected')."\n";
echo 'notExists: '.methodType($myclass, 'notExists')."\n";
?>

Here we have methodType() function, giving the class and method, it will return a string “public”, “private”, “protected” or “error”. This function uses ReflectionMethod class from PHP, it can do lots of things more.4

Well, back to the second example, I’d like to record calls of some methods, so I will create a superclass MyClassBase with a invoker method used to call other methods inside the other class only if they are public:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
function methodType($class, $method)
{
  try
    {
      $method = new ReflectionMethod($class, $method);
     
      if ($method->isPrivate())
    return 'private';
      elseif ($method->isProtected())
    return 'protected';
      elseif ($method->isPublic())
    return 'public';
    }
  catch (Exception $e)
    {
      return 'error';
    }
}

class MyClassBase
{
  function __construct()
  {
    echo "Class created\n";
  }
 
  public function invoker($method, $arguments=array())
  {
  try
    {
      $method = new ReflectionMethod($this, $method);
     
      if ($method->isPublic())
    {
      echo "I'm invoking method ".$method->name."...\n";
      return $method->invokeArgs($this, $arguments);
    }
      else
    echo "Method ".$method->name." is not public!!\n";
    }
  catch (Exception $e)
    {
      echo "Error invoking ".$method."\n";
    }
  }
}

class MyClass extends MyClassBase
{
  function __construct()
  {
    echo "Creating MyClass...\n";
  }

  private function myPrivate()
  {
    echo "shhh... this is private\n";
  }

  public function myPublic()
  {
    echo "Hello everybody!!\n";
  }

  public function myPublicCalls()
  {
    echo "I'm a public method that calls private methods...\n";
    $this->myPrivate();
  }

  public function myPublicArguments($arg1, $arg2)
  {
    echo "I'm a public method with two arguments: ".$arg1." and ".$arg2."\n";
  }

  protected function myProtected()
  {
    echo "Protected method!!\n";
  }

}

$myclass = new MyClass();

$myclass->invoker('notExists');
$myclass->invoker('myPrivate');
$myclass->invoker('myPublic');
$myclass->invoker('myPublicCalls');
$myclass->invoker('myPublicArguments', array('argument1', 'argument2'));
?>

The answer will be:

Creating MyClass…
Error invoking notExists
Method myPrivate is not public!!
I’m invoking method myPublic…
Hello everybody!!
I’m invoking method myPublicCalls…
I’m a public method that calls private methods…
shhh… this is private
I’m invoking method myPublicArguments…
I’m a public method with two arguments: argument1 and argument2

In fact, when a private or inexistent method is called, invoker() will give an error, and we can capture it easily, avoiding a PHP error to be triggered, or we can throw an exception. And if the method is public, we can run code before and after calling it, so we can log this call.

Another interesting thing is invoking the method with arguments, these arguments must be specified inside an array, so instead of calling:

1
2
3
<?php
myPublicArguments('argument1', 'argument2');
?>

When using the invoker we must do:

1
2
3
<?php
$myclass->invoker('myPublicArguments', array('argument1', 'argument2'));
?>

Swapping variable values in PHP [Short post]

October 11, 2013 No comments

Yesterday we talked about swapping variables in C and C++. This time, we will do it in PHP.

We can translate the C program to PHP, creating a temporary value and running the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$a = 11;
$b = 99;

echo "Original A value: ".$a."\n";
echo "Original B value: ".$b."\n";

$tmp = $a;
$a = $b;
$b = $tmp;

echo "New A value: ".$a."\n";
echo "New B value: ".$b."\n";
?>

It will simply work, but we can take advantages of built-in PHP functions, to make it shorter (and we won’t use a temporary variable):

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$a = 11;
$b = 99;

echo "Original A value: ".$a."\n";
echo "Original B value: ".$b."\n";

list($a, $b) = array($b, $a);

echo "New A value: ".$a."\n";
echo "New B value: ".$b."\n";
?>

So first we create an array with values $b and $a and then we separate this values in variables $a and $b. The result is the same.

Hello world!

October 9, 2013 1 comment

Not just WordPress’ default post title. As a programmer, I’ve written hundreds of “hello world” programs to test compilers, to test libraries, to test new programming languages… that’s an easy way to know things work and to know I can make it work.

I will write here about programming (my favourite languages are C, C++ and PHP, so I will talk about them. Maybe I’ll write something about another languages too); Unix-like operating systems, I use GNU/Linux everyday and I really like the way it works and how customizable it is (but most things are applicable to other *nixes).

So I welcome youto my new blog, hoping you find it useful, and leave some comments here, and share my posts if you like them.

 

Photo: Angel Raul Ravelo Rodriguez (Flickr) Licensed: CC-by.

3XBU27AYR3ZJ code for Technorati

Top