Calling an object that has a protected property that you need access to? This function will allow you to quickly access data stored in protected properties of PHP objects.
Note: I tested this on PHP 7.4. It will likely work on other versions, but may need tweaking.
Good developers will protect the internals of their objects with private and protected scopes. That means from outside of the object your code will not be able to access whatever is protected. What I am about to show you breaks that encapsulation. Generally, this is not something you want to do, however, if you are working with an object you have no control over, it may be necessary. I ran across this while working with an object from an external library.
This method works by typecasting the object to an array. You can then access the property using a little known method.
Let’s see the code!
function getProtectedValue( $object, $prop_name ) {
$array = ( array ) $object;
$prefix = chr( 0 ) . '*' . chr( 0 );
return $array[ $prefix . $prop_name ];
}
Photo courtesy of Unsplash https://unsplash.com/photos/Vp3oWLsPOss
Find and update WordPress posts with comments older than NNN days
By Ben Lobaugh (blobaugh)
On March 12, 2018
In Computing, MySQL, Programming, Web Development, WordPress
I have a use case where I need to disable comments on posts in WordPress where the last comment was more than one year, or 365 days, ago.
Posts can be found with this query:
The outer query takes the inner query as the search parameter. The inner query is finding the latest comment for each post based on the number in the WHERE condition. 365 represents 365 days, or 1 year.
Therefore, this query is getting the latest comment for post where the comment is less than 1 year old.
Now let’s say you need to update the posts to disable comments. The goal is to disable commenting for all posts that have not had a comment within the last year. It can be accomplished with the following:
Here again the number 365 represents the number of days.
Check the posts and you should see the comments have been closed.