<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bugs On Steroids &#187; PHP</title>
	<atom:link href="http://blog.e-svet.si/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.e-svet.si</link>
	<description>Not Another Programming Blog</description>
	<lastBuildDate>Wed, 26 Feb 2014 14:15:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.6</generator>
		<item>
		<title>Object Oriented Programming In PHP Part Three – Constructor &amp; Destructor</title>
		<link>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/</link>
		<comments>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/#comments</comments>
		<pubDate>Sun, 15 Sep 2013 09:39:00 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=162</guid>
		<description><![CDATA[PHP offers many &#8220;special&#8221; methods called magic methods. Today I will write about two of them. This is the third part of the Object Oriented Programming in PHP series and, if you haven&#8217;t already, I suggest you first read part one and two. The methods we will take a look at today are called constructor ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>PHP offers many &#8220;special&#8221; methods called magic methods. Today I will write about two of them. This is the third part of the Object Oriented Programming in PHP series and, if you haven&#8217;t already, I suggest you first <a href="http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/" title="Object Oriented Programming In PHP Part One – Basics">read part one</a> and <a href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/" title="Object Oriented Programming In PHP Part Two – Methods And Visibility">two</a>. The methods we will take a look at today are called constructor and destructor.<span id="more-162"></span></p>
<p><a href="http://www.php.net/manual/en/language.oop5.magic.php" title="PHP magic methods" target="_blank">All magic methods</a> names start with two underscores. To implement constructor and destructor we have to override __construct() and __destruct() methods. The method __construct is invoked when we create an object and __destruct when all references on an object are removed or an object is explicitly destroyed.</p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBaracks {
 
  // note that construct methods starts with two underscores
  public function __construct() {
    // this code executes when object is created
    echo &quot;Soldier &quot; . $this-&gt;name . &quot; was created.&quot;;
  }

  // ... rest of the class code
  
  public function __destruct() {
    // this code executes when object is destroyed
    echo &quot;Destroying solider with name &quot; . $this-&gt;name;
  }
}
</pre>
<p>We use constructor in cases, when we want to execute some piece of code when object is instantiated. For instance, set values to properties for which we want to be sure they are set. In case of a class which takes care of connecting to database, we would want to be sure that we have all data required for establishing connection. We could use destructor to close the connection. In practice, constructor is much more often used than destructor because PHP closes resources it uses when script finishes execution. Anyway, <a href="http://stackoverflow.com/questions/3566155/php-destructors" title="Uses of PHP __destruct() method" target="_blank">this stackoverflow link</a> offers few examples of uses of destruct method in open source code.</p>
<p>For the sake of clarity, let&#8217;s build upon our MilitaryBaracks example. We want to be sure that every soldier has name and weapon.</p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBaracks {
 
  // name doesn't have default value no more
  private $_name;
  // so doesn't weapon
  private $_weapon;
 
  private $_ammunition = 10;
 
  // instead, we make sure that values are passed when object is created
  public function __construct($name, $weapon) {
    $this-&gt;_name = $name;
    $this-&gt;_weapon = $orozje;
  }

  // we want that soldier is able to switch weapon
  // so we create getter method to access weapon variable value
  public function getWeapon() {
    return $this-&gt;_weapon;
  }
 
  // and set method to switch weapon
  public function setWeapon($weapon) {
    $this-&gt;_weapon = $weapon;
    return $this;
  }
 
  // name can't be changed, so we create only getter method
  public function getName() {
    return $this-&gt;_name;
  }
 
  //...
}
</pre>
<p>Ookay, let&#8217;s print out a few lines:</p>
<pre class="brush: php; title: ; notranslate">
// this is wrong because of missing arguments
$soldier = new MilitaryBaracks();
// the right way
$soldier = new MilitaryBaracks('Mougli', 'rifle');
 
echo $soldier-&gt;getname() . &quot; has weapon &quot; . $soldier-&gt;getWeapon() . &quot;.&lt;br&gt;&quot;;
 
$soldier-&gt;setWeapon('gun');

echo $soldier-&gt;getName() . &quot; has weapon &quot; . $soldier-&gt;getWeapon() . &quot;.&quot;; 
</pre>
<p>And we get:</p>
<div style="border: 1px solid #c9c9c9; padding: 10px; background-color: #f7f7f7;">
Warning: Missing argument 1 for MilitaryBaracks::__construct(), called in C:\Programi\Wamp\www\script.php on line 41 and defined in C:\Programi\Wamp\www\script.php on line 13</p>
<p>Warning: Missing argument 2 for MilitaryBaracks::__construct(), called in C:\Programi\Wamp\www\script.php on line 41 and defined in C:\Programi\Wamp\www\script.php on line 13</p>
<p>Notice: Undefined variable: name in C:\Programi\Wamp\www\script.php on line 14</p>
<p>Notice: Undefined variable: weapon in C:\Programi\Wamp\www\script.php on line 15</p>
<p>Mougli has weapon rifle.<br />
Mougli has weapon gun.
</p></div>
<p>This way our object are easier to instantiate and set, since we do everything in one line. Beside that, now we can be pretty sure that our objects have all needed properties set, as PHP throws a warning if we leave out an argument when instantiating new object. Our code and classes needs to be organized in a way that other programmers can easily understand its meaning and structure. The predictability is important &#8220;guide&#8221; of OOP.</p>
<p>Even though I previously announced a blog post about inheritance I saved it for next time. I intended to present constructor and inheritance in this post, but it would be too long and I want to keep series short and simple. For that reason I cover it in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming In PHP Part Two – Methods And Visibility</title>
		<link>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/</link>
		<comments>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/#comments</comments>
		<pubDate>Sun, 08 Sep 2013 09:26:30 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=94</guid>
		<description><![CDATA[In part one of Object Oriented Programming in PHP series I introduced fundamental terms of OOP (class, object and property). Today I will continue with explaining visibility keywords and methods. The methods differ from the functions in that they are declared in the class. They support different types of visibility just like properties do. Visibility ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>In part one of <a href="http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/" title="Object Oriented Programming In PHP Part One – Basics">Object Oriented Programming in PHP</a> series I introduced fundamental terms of OOP (class, object and property). Today I will continue with explaining visibility keywords and methods. <span id="more-94"></span></p>
<p>The methods differ from the functions in that they are declared in the class.</p>
<pre class="brush: php; title: ; notranslate">
public function myMethod() {
 
}
</pre>
<p>They support different types of visibility just like properties do. Visibility keywords are: <b><i>public, protected and private</b></i>. These keywords define from where we can access the method. Public methods can be accessed from anywhere while private methods can only be accessed in the same class they are defined in. There is also protected keyword, but we will take a closer look at it a bit later. First, let&#8217;s just take a look at the example of using public and private keywords.</p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBaracks {
 
  //properties that we can access anywhere
  public $name = 'Mougli';
  public $weapon = 'rifle';
 
  //properties that we can access in this class only
  //in practice we usually prepend _ to the private methods for the clarity
  private $_ammunition = 10;
 
  //because we are inside the class, which defines property $_ammunition, we can access that property
  public function getAmmunition() {
    return $this-&gt;_ammunition;
  }
 
  public function shoot() {
    //keyword this means that we refer to property of an instance of class -&gt; an object
    //if soldier has any ammunition left, shoot and subtract one bullet
    if($this-&gt;_ammunition &gt; 0) {
      $this-&gt;_ammunition = $this-&gt;_ammunition - 1;
       
      return true;
    }
    return false;
  }
}
</pre>
<p>Let&#8217;s take a look at the above code in more detail. I&#8217;ve added a private property $_ammunition and methods getAmmunition() and shoot(). Because we cannot access a private property, we need to create a public method, which returns its value (getAmmunition()). Method shoot() reduces a number of bullets left each time it is called.</p>
<p>It is a common practice to prepend _ to the private properties. This helps to quickly differentiate private properties from public. Maybe all this is confusing, so let me clear it up a bit with an example. Let&#8217;s see what happens if I try to change and print out both properties.</p>
<pre class="brush: php; title: ; notranslate">
// we instantiate an object of type MilitaryBaracks
$soldier = new MilitaryBaracks();
 
// and print out its name (its property)
echo $soldier-&gt;name;
echo &quot;&lt;br&gt;&quot;;
// we change its name to &quot;Matic&quot;
$soldier-&gt;name = 'Matic';
echo $soldier-&gt;name;
echo &quot;&lt;br&gt;&quot;;
echo $soldier-&gt;_ammunition;
</pre>
<p>This is what we get:</p>
<div style="border: 1px solid #c9c9c9; padding: 10px; background-color: #f7f7f7;">
Mougli</p>
<p>Matic</p>
<p>Fatal error: Cannot access private property MilitaryBaracks::$_ammunition in C:\Programi\Wamp\www\script.php on line 42
</p></div>
<p>As you see we can access and modify public properties values just like variables, but we cannot do that with private ones. This is a mechanism to protect properties which values shouldn&#8217;t be changed from outside the class. But sometimes (actually quite often) we want to access the private properties from outside of class scope. In that case we create a public method like we did in our case. That way we can enforce the rules &#8211; what someone can do with that property. In our case we want to allow just reading so we created a getAmmunition() method.</p>
<pre class="brush: php; title: ; notranslate">
$soldier = new MilitaryBaracks();
echo &quot;Soldier has &quot; . $soldier-&gt;getAmmunition() . &quot; bullets.&quot;;
echo &quot;Soldier shoots.&quot;;
$soldier-&gt;shoot();
echo &quot;Soldier has &quot; . $soldier-&gt;getAmmunition() . &quot; bullets.&quot;;
</pre>
<div style="border: 1px solid #c9c9c9; padding: 10px; background-color: #f7f7f7;">
Soldier has 10 bullets.<br />
Soldier shoots.<br />
Soldier has 9 bullets.
</div>
<p>What does keyword <b><i>$this</b></i> means? With the use of $this keyword a class knows it&#8217;s operating on <b><i>this</b></i> object. For simplicity try changing word $this with &#8220;current object instance&#8221;.</p>
<p>When I was learning about OOP I was asking myself why would I set a method or property to private, if that just makes things more complicated. You have to write more code, because you have to write an additional method to access the property. Here is the answer. The thing with OOP is that we want to limit the access to class properties and methods as much as possible. This way me try to make code more clear and harder to use in a wrong way.</p>
<p>That is not so obvious in my case, because the example is to simple. But I hope it will become more clear in an upcoming posts, where we will roll up our sleeves and get to some more serious programming <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>In next post of this series we will cover one of the most important but also more complex topic of object oriented programming, that is <b><i>inheritance</b></i>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming In PHP Part One &#8211; Basics</title>
		<link>http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/</link>
		<comments>http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/#comments</comments>
		<pubDate>Sat, 24 Aug 2013 13:07:40 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=21</guid>
		<description><![CDATA[Usually, when people visit some website, they quickly form an opinion about it. They either like it, or they don&#8217;t. They find it well structured/organized, neat &#8230; or give up in search for a contact form &#8230; But nobody knows how good is the code, that is running the site &#8230; I believe that when ...<a class="post-readmore" href="http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>Usually, when people visit some website, they quickly form an opinion about it. They either like it, or they don&#8217;t. They find it well structured/organized, neat &#8230; or give up in search for a contact form &#8230; But nobody knows how good is the code, that is running the site &#8230;<span id="more-21"></span> I believe that when programming in PHP, one of the biggest steps towards writing clean and reusable code, is writing object oriented code. That is why I will dedicate a series of blog posts to this topic.</p>
<p>In the first part of this series I will try to lay out the most basic terms as simple as possible. I will describe what is an object, class and a property.</p>
<h2>Class</h2>
<p>Personally I see a class as some kind of a frame, with which help we generate objects. I would say that the best comparison is the one with a computer game e.g. old strategic game &#8211; Age Of Empires. Each building, that we create has a special task. Let&#8217;s say it generates soldiers. So, we create a class MilitaryBarack (a building in the game) and that class generates objects (soldiers in the game).</p>
<p>We create a class with a reserved word <strong>class ClassName and brackets {}.</strong></p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBarack 
{
}
</pre>
<p>Even though this piece of code is perfectly legit, it is pretty useless, because it doesn&#8217;t do anything. We will fix that later.</p>
<h2>Object</h2>
<p>As I mentioned before, class generates, or more accurately, instantiates an object. But what is an object? Let me return back to game comparison. MilitaryBracket generates an object, a soldier, which has certain properties. In programming terms we say that an object is an instance of a class. We instantiate it with the use of a reserved word <strong>new</strong> plus the ClassName.</p>
<pre class="brush: php; title: ; notranslate">
$soldier1 = new MilitaryBaracks();
$soldier2 = new MilitaryBaracks();
</pre>
<p>When we create new instance of an object, it gets a unique identity. We can print object id and all of its properties with very useful function <b>var_dump();</b>.</p>
<pre class="brush: php; title: ; notranslate">
var_dump($soldier1);
var_dump($soldier2);
</pre>
<p>If we open that in browser, we will see the output</p>
<pre class="brush: php; title: ; notranslate">
object(MilitaryBaracks)[1] // note the object id in square brackets. Object has no properties yet.

object(MilitaryBaracks)[2]
</pre>
<h2>Properties</h2>
<p>All of this code is still quite useless. To make it more useful, we will add it some properties. Property of an object can contain different types of data. In our case, we could use a soldier&#8217;s name and a type of weapon he carries. To assign properties to an object, we have to declare it in its class. PHP offers three types of properties: <i>public, protected and private</i>. I will write more about the meaning of this words in next posts. For now it is enough to know, that they exist. We declare property with one of these reserved words plus a variable.</p>
<pre class="brush: php; title: ; notranslate">
// class
class MilitaryBaracks {
  // and its properties with defined default values
  public $name = 'Mougli';  
  public $weapon = 'rifle';
}
</pre>
<p>As you se, we defined two properties to MilitaryBaracks class. If we now instantiate and print a new object, we can see all values it holds. To access the property value we use an arrow (->).</p>
<pre class="brush: php; title: ; notranslate">
$soldier = new MilitaryBaracks();
echo &quot;Soldier &quot; . $soldier-&gt;name . &quot; carries a &quot; . $soldier-&gt;weapon;
</pre>
<p>These is were I stop for today. In <a href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/" title="Object Oriented Programming In PHP Part Two – Methods And Visibility">part 2</a> of these series I will write about methods and visibility.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
