KIO
Kreative Ideen online
Encapsulation and scope

Encapsulation and scope

In software design,think of encapsulation as the principle by wich code and data are bundled together in a way that restricts their access to the rest of the programming. The simplest example of encapsulation is a function Consider this PHP code:

[php]
$post = get_post( 1 );

function slug_get_post_five(){
$post = get_post(5 );
var_dump( $post );
}

var_dump( $post );
slug_get_post_five( 5 );
[/php]

In this example, which isn’t using any Object-Oriented PHP, we have two different variables called “post” that are being printed with “var_dump();”. They will print two totally different things because the second “$post” is encapsulated inside of a function, while the first is not.

In this case, the second $post was encapsulated in the function “slug_gget_post_five()” and place in a different scope than the $post above it, which makes it a completeley different variable. They look similar because they ashere the same name, but they have no relationship. In fact, the are stored as two separate entities in the server’s RAM when being executed.

In non-OOP PHP, we have no good way fo declaring a controlling access outside of a function to a variable declared in the function.

Leave a Reply

Your email address will not be published. Required fields are marked *